I came across this line in reachability.cpp in assignment 1 of Algorithms on Graphs on Coursera where n is num vertices and m is num edges from cin.
vector<vector<int> > adj(n, vector<int>()); What is that second argument? I think this makes a 2D vector with n rows, each having a vector(int) but none of the other answers on here mention the second argument and I couldn't find anything on cpp reference and other sources.
I tried to explicity state the size of the columns and initialize with 0 like this:
vector<vector<int> > adj(n, vector<int>(n, 0)); because I wanted to print out the shape with the function below to confirm that I have an adjacency matrix.
void print(vector<vector<int> > &a) { std::cout<<"Vec elements:\n"; for(unsigned int j =0; j<a.size(); j++) { for(unsigned int k =0; k<a[j].size(); k++) { std::cout<<a[k][j]<<" "; } } } I have other code where I just make a 2D vector like this:
vector<vector<int> > graph; Then I resize each row to have n columns with a loop to make the adjacency matrix.
for(i=0;i<n;i++) graph[i].resize(n); //resize 2d array Because this is boilerplate code provided by the instructors, there must be some merit to what they are doing. So I'd like to know what it is.
Edit:
Saw this in Gaddis' book:
So I guess it is making a vector of n elements with each element being a vector<int>.

std::vectorconstructor reference should hopefully be helpful.std::string, you'll find the most-often used class template in your C++ arsenal will bestd::vector, and as such it deserves extra study time. Fwiw, in your first example, that second argument is pointless. If omitted, the vector will use default construction for thenelements, which is exactly whatstd::vector<int>()provides as a temporary copy src. It is more suitable to see this constructor when default construction is not sufficient (eg. your second example), or even possible (such as a type with no default ctor).