Duncan
Duncan

Reputation: 1034

Why do these two segments of code give me different results?

I have an object G which is a graph. I overloaded the bracket operators so that G[i] returns a list<int> (STL list) which is a list of vertex i's adjacencies.

I have these two segments of code which are both supposed to iterate over G[i], but only the first one works.

list<int> adj = G[2];

for(list<int>::iterator it = adj.begin(); it != adj.end(); it++) {
    cout << *it << " ";
}

This does not work...

for(list<int>::iterator it = G[2].begin(); it != G[2].end(); it++) {
    cout << *it << " ";
}

As far as I can see, they do the same thing. Can anyone explain why the second code segment does not work? Also, is there a better way of iterating over my list?

Upvotes: 2

Views: 95

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

I overloaded the bracket operators so that G[i] returns a list<int>

Make sure that the return type of your operator [] is list<int>&, not list<int>. Otherwise, a copy will be created upon return each time you call G[2], so G[2].end() will never be reached.

If you invoke [] once, the way you do in the first code fragment featuring adj, the problem will not be visible (although a list will be copied two times - once in the return, and once more in the assignment operator). The second fragment exposes the problem by calling the [] operator multiple times.

Upvotes: 5

Haocheng
Haocheng

Reputation: 1343

Maybe Graph::opertor[] returns a new list everytime, so you can't compare iterator between different lists.

list<int> adj = G[2];
list<int>::iterator end = adj.end();

for(list<int>::iterator it = adj.begin(); it != end; ++it) {
  cout << *it << " ";
}

Upvotes: 3

Related Questions