Using Iterators

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

In the above code the iterator ‘it’ is incremented as ++it and not as it++. But wouldn’t ++it increment the iterator first and then execute the loop and in the process miss it == 0?
Shouldn’t it be it++?


It doesn’t matter whether you use ++it or it++ , the increment happens only after the loop body is executed but practically for large and complex problems, pre-increment is always preferred to reduce ambiguity.

1 Like

list::iterator it = l.began();
While(it != l.end())

It= it + 1;
Consider the above while loop this is how for loop works, so no matter whether you write ++it or it++ it is one and the same. The only key point here is that it the last statement in that block.

1 Like