Constructor and vector<vector<int>>

Hello,
I need help with creating a constructor. It seems to be an easy task but I could not find the proper initialization that could be run by my compiler.

The whole code is about the graphs, namely representation of graphs using Adjacency List.


One of the classes (AdjacentListGraph) contains 3 private variables:
int n; // number of vertices in the graph
vector<vector<int>> neighbors; // this list stores all the adjacent vertices to
// each vertex, e.g. neighbors[u][v] means that u
// is a vertex and v is a vertex such that v is
// on the list that belongs to u
vector<vector<int>> weights; // since it is a weighted graph, weights[u][v]
// is the weight of the edge between u and v


My problem is to implement the constructor such that 'neighbors and weights' lists are initialized to zero:
AdjacentListGraph::AdjacentListGraph(int n)
{
this->n=n;
// implementation for neighbors and for weights

}


Thanks in advance for all the answers.
My problem is to implement the constructor such that 'neighbors and weights' lists are initialized to zero:


With std:: vector , one doesn't need to worry about that. Just push_back or brace initialise whatever actual values you need.

With your constructor, use a constructor parameter list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
AdjacentListGraph::AdjacentListGraph(int n)
     :    // colon introduces constructor parameter list
     // call any base class constructors here
     n(n) ,   //make sure to do all the member of the class, in the same order a the class declaration
     
     // other member inits here
{

// the function body is empty, unless you want to do validation here, or call some other function
this->n=n; // use constructor parameter list
  // init of neighbors and weights not needed, but should have an interface function to load data
// implementation for neighbors and for weights

}



The other possible option is to use std::initializer_list, but that probably means typing in a big brace list, so probably better to do something else, like load from a file.

http://en.cppreference.com/w/cpp/utility/initializer_list


There is an example with output at the end. The struct S has a std::initializer_list constructor.

Good Luck !!

Edit: please always use code tags - Cheers:

http://www.cplusplus.com/articles/z13hAqkS/
Last edited on
Topic archived. No new replies allowed.