RAHUL RAHUL - 2 months ago 8
C++ Question

iterating over vector of vectors in c++

I've just started to code in C++, so i'm new to STL .
Here i'm trying to iterate over a graph stored as vector of vectors.

#include <iostream>
#include <vector>
#include <iostream>

using namespace std;

int reach(vector<vector<int> > &adj, int x, int y) {
vector<vector<int> >::iterator it;
vector<int>::iterator i;

for (it = adj.begin(); it != adj.end(); it++)
{
cout << (*it) << endl;
if ((*it) == x)
for (i = (*it).begin(); i != (*it).end(); i++)
{
cout << (*i) << endl;
if ((*i) == y)
return 1;

}
}
return 0;
}

int main()
{

}


I'm getting an error
std::vector<int>
is not derived from const gnu cxx. Can someone point me in the right direction ?

Answer
 cout << (*it) << endl;

Here, you declared it as a:

 vector<vector<int> >::iterator it;

Therefore, *it is a:

 vector<int>

So you are attempting to use operator<< to send it to std::cout. This, obviously, will not work. This is equivalent to:

 vector<int> v;

 cout << v;

There is no operator<< overload that's defined for what cout is, and a vector<int>. As you know, in order to print the contents of a vector, you have to iterate over its individual values, and print its individual values.

So, whatever your intentions were, when you wrote:

cout << (*it) << endl;

you will need to do something else, keeping in mind that *it here is an entire vector<int>. Perhaps your intent is to iterate over the vector and print each int in the vector, but you're already doing it later.

Similarly:

 if ((*it) == x)

This won't work either. As explained, *it is a vector<int>, which cannot be compared to a plain int.

It is not clear what your intentions are here. "Graph stored as a vector or vectors" is too vague.

Comments