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.

2
  • 1
    it < obj.end() should be it != obj.end(), Also do not use it++, use ++it(more here) 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... Commented Feb 21, 2013 at 15:48
  • What error? Does the compiler tell you anything? Commented Feb 21, 2013 at 15:50

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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++)

Comments

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.

Comments

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 } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.