bobobobo
bobobobo

Reputation: 67254

are two different iterators on the same collection equal

Say I use a nested for to compare objects in the same list:

for( list<Object>::iterator iter = list.begin() ; iter != list.end() ; ++iter )
  {
    for( list<Object>::iterator iter2 = list.begin() ; iter2 != list.end() ; ++iter2 )
    {
      if( iter == iter2 )
      {
        // does this mean iter is pointing to the same INDEX
        // as iter2?  Will this work as expected?
      }
    }
  }

Upvotes: 2

Views: 842

Answers (2)

Loki Astari
Loki Astari

Reputation: 264471

Short Answer: NO.

Medium Answer:

The normal containers in std:: provide iterators that are directly comparable like that. But you can not make this general assumption about other container types.

Long Answer:

It all depends on the type of the container and thus the type of the iterators returned by that container. If you are talking about the containers in standard (std::) then yes. But do not assume this holds for all types of iterators. Remember in C++ it is more common to pass around iterators rather than references to containers.

template<typename I>
I doStuff(I begin, I end)
{
      typedef tyepename std::interator_traits<I>::iterator_category   iterator_category;

      I   alternative = begin;

      assert(alternative == begin);   // Will always be true

      ++begin;
      ++alternative;

      assert(alternative == begin);  // Will depend on the type of iterator.
      return end;
}

// Alternative using container
template<typename C>
void doStuff(C& cont)
{
      typedef tyepename std::interator_traits<typename C::iterator>::iterator_category   iterator_category;

      I   begin       = cont.begin();
      I   alternative = cont.begin();

      assert(alternative == begin);   // Will always be true

      ++begin;
      ++alternative;

      assert(alternative == begin);  // Will depend on the type of iterator.
}

Input and output iterators are not directly comparable like that.

But Bi-Directional and Random Access iterators are directly comparable.

see: http://www.sgi.com/tech/stl/iterator_category.html

Note: the iterator returned by end() will always be directly comparable and return true for one past the end of the container. But this may not hold for other iterators.

Upvotes: 2

Useless
Useless

Reputation: 67743

... to compare objects in the same list:

Yes, that means exactly what you expect, and works fine.

Upvotes: 5

Related Questions