-2

I'm doing some work on data structures, just to learn. Right now I have an admittedly very basic graph data structure.

I can create the graph with a predefined size, and then add edges to/from each vertex (un-directed). Here is the code so far:

graph.h

#pragma once
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <algorithm>

class Graph {
    int vertices; // num of vertices in graph
    std::vector<int> *adjList;
public:
    Graph(int vertices);
    void addEdge(int v, int w);
    void printGraph();
};

Graph::Graph(int vertices) {
    this->vertices = vertices;
    adjList = new std::vector<int>[vertices];
}

void Graph::addEdge(int v, int w) {
    adjList[v].push_back(w);
}

void  Graph::printGraph() {
    for (int i = 0; i < adjList->size(); ++i) {

    }

}

graph.cpp

#include "stdafx.h"
#include "graph.h"

int main()
{
    Graph graph(4);
    graph.addEdge(0, 1); //counter starts at 0
    graph.addEdge(0, 2);
    graph.addEdge(2, 1);
    graph.addEdge(2, 3);

    return 0;
}

This works fairly well, however I would also like to add nodes after the graph object has already been created. I really can't figure out how to do this.

Any sort of guidance towards this (as well as general improvements to the code) will be greatly appreciated.

deadturkey
  • 62
  • 6
  • 1
    A dynamically allocated array of `std::vector`s? That's a new one. Because of that, to add a vertex you would need to reallocate a larger array, copy the elements over and then delete the original array. – Mike Borkland Nov 23 '18 at 22:02
  • 1
    You almost never want to dynamically allocate a `vector`. `vector`'s main job is to hide dynamic allocation from you and do all the work involved so you don't have to. Dynamically allocating a `vector` undoes part of that noble effort. Side note: [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – user4581301 Nov 23 '18 at 22:18
  • What makes you think you need to dynamically allocate the vector? There's such thing as a vector of vectors, or `std::vector>`. – BessieTheCookie Nov 23 '18 at 23:31

1 Answers1

1

Use a vector to store your adjacency list and resize it when required:

std::vector<std::vector<int>> adjList;

Don't allocate it with new, don't delete it, use standard containers!

Matthieu Brucher
  • 19,950
  • 6
  • 30
  • 49