Gaurav Sahu
Gaurav Sahu

Reputation: 191

initialising array of vectors in constructor

I have a class named Graph. There this vertices member of the class. I have initialized vertices in the constructor. Also, There is a member array of vectors. I want the number of vectors to be equal to vertices. for example if vertices = 5 then my array of vectors should look like this. vector v[5]; How can I do this in the constructor as I will only know the value of vertices in the constructor?

class Graph
{

private:
    int vertices;
    std::vector<int> adj[];
public:
    Graph(int v); //constructor
    // add an edge
    void addEdge(int u, int v);
    //print bfs traversal of graph
    void bfs(int s); // s is a source from where bfs traversal should 
                     //start

};

Graph :: Graph(int v)
{
   vertices = v;
}

Upvotes: 0

Views: 36

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

Since you only know the value of your vertices at run-time, you cannot use a C-style array or a std::array, as those require the size to be known at compile-time.

You can use another vector instead:

std::vector<std::vector<int>> adj;

Upvotes: 1

Related Questions