Vector iterator providing wrong value
c++, graph, iterator, pointers, vector
Solution
Since `adjL` curiously returns by value, the following line is broken:
for(vector<int>::iterator it = adjL(count).begin(); it != adjL(count).end(); ++it) {
You're comparing iterators from two different containers, and you're storing an iterator to a temporary that immediately goes out of scope, its value(s) immediately becoming impossible to read without causing Heisenberg to possibly turn in his grave.
`adjL` should return a `const vector<int>&`.
Problem
I'm facing issue with my Graph implementation, specifically the function `printGraph()`. This function contains a loop to print the adjacency list representation of the graph. If I loop though using the member object variable `adj` then it shows me the correct output which is: ``` 0 : 1 2 2 1 : 0 2 2 : 0 1 0 3 3 : 2 3 3 ``` However, If I use the getter method `adjL()` then it provides me a wrong output which is: ``` 0 : 0 0 2 1 : 0 0 2 : 0 0 0 3 3 : 0 0 3 ``` Most likely I am making a stupid mistake but I can't seem to catch it. Any help is appreciated. I think I am not able to understand how to use the value returned by the getter method `adjL()`. ``` class UndirectedGraph { //vector<vector <int> > adj; public: vector<vector <int> > adj; UndirectedGraph(int vCount); /* Constructor */ void addEdge(int v, int w); /* Add an edge in the graph */ vector<int> adjL(const int v) const ; /* Return a vector of vertices adjacent to vertex @v */ void printGraph(); }; UndirectedGraph::UndirectedGraph(int vCount): adj(vCount) { } void UndirectedGraph::addEdge(int v, int w) { adj[v].push_back(w); adj[w].push_back(v); edgeCount++; } vector<int> UndirectedGraph::adjL(const int v) const { return adj[v]; //return *(adj.begin() + v); } void UndirectedGraph::printGraph() { int count = 0; for(vector<vector <int> >::iterator iter = adj.begin(); iter != adj.end(); ++iter) { cout << count << " : "; /* for(vector<int>::iterator it = adj[count].begin(); it != adj[count].end(); ++it) { cout << *it << " "; } */ for(vector<int>::iterator it = adjL(count).begin(); it != adjL(count).end(); ++it) { cout << *it << " "; } ++count; cout << endl; } } int main() { UndirectedGraph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); g.printGraph(); } ```