2

ネストされた for を使用して、同じリスト内のオブジェクトを比較するとします。

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?
      }
    }
  }
4

2 に答える 2

5

... 同じリスト内のオブジェクトを比較するには:

はい、それはまさにあなたが期待していることを意味し、正常に動作します。

于 2012-10-29T16:24:42.090 に答える
2

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.

于 2012-10-29T17:36:10.827 に答える