2

I thought the idea of the iterator object was that you can apply it similarly to the C++ container classes. When I try to iterate through a list object, however, I tried using

for(list<int>::iterator it = obj.begin(); it < obj.end(); it++){
    // some code
}

And I got an error. Why doesn't this work? Why would it work for vector::iterator? Is it just because of the implementation of list being bi-directional linked lists? I thought the iterator object abstracts that notion of moving through containers, thereby allowing it to operationally be the same, whether for vectors or lists.

I'd really appreciate a clarification.

timrau
  • 22,578
  • 4
  • 51
  • 64
naxchange
  • 893
  • 1
  • 11
  • 24
  • 1
    it < obj.end() should be it != obj.end(), Also do not use it++, use ++it(more [here](http://stackoverflow.com/questions/1077026/incrementing-iterators-it-more-efficient-than-it)) and use non-member begin and end if you use c++11... and maybe you don't want end function to be called every time... – joy Feb 21 '13 at 15:48
  • What error? Does the compiler tell you anything? – sth Feb 21 '13 at 15:50

4 Answers4

7

This does not work because, unlike std::vector iterators, std::list iterators are not random-access - they are sequential. You need to use != on them:

for(list<int>::iterator it = obj.begin(); it != obj.end(); it++)

In general, it's a good idea to use "not equals" on all iterators when you are looking to cover the entire range, even when these iterators allow comparisons for < and >. There is also an argument in favor of using != in your regular for loops, too, because it gives you the strongest postcondition.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You have to compare with != as list iterators are scattered throughout all memory in random order.

Use: for(list<int>::iterator it = obj.begin(); it != obj.end(); it++)

Didier Trosset
  • 36,376
  • 13
  • 83
  • 122
0

That's because list does not support random access iterators, but only forward iterators. Therefore, operator < is not defined for iterators of a list. You have to use operator != for inequality comparisons.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
0

Operator arithmetic, including ordering-comparison operators (like <), is only defined for random access iterators. If you change the code to use !=, it will work (assuming obj is a list<int>):

for(list<int>::iterator it = obj.begin(); it != obj.end(); it++){
    // some code
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455