In C++ why can't we compare iterators using > and <? [duplicate]

一世执手 提交于 2019-12-04 03:48:09

operator< and operator> can only be used with RandomAccessIterator. But operator!= could also be used with InputIterator, ForwardIterator and BidirectionalIterator. For your sample code, it != myVector.end() and it < myVector.end() have the same effect, but the former is more general, then the code also works with other iterators (e.g. iterators of std::list or std::map etc).

BTW: Your sample code will be fine to use operator< or operator>, since the iterator of std::vector is RandomAccessIterator.

std::vector::iterator is a random access iterator, and you can certainly compare them with < and >.

However, only random access iterators can be compared using anything other than == and !=. Bidirectional, forward, and input iterators only define the equality/inequality comparison operators.

A std::list::iterator, for example is an iterator pointing to some unspecified member of a std::list. In this case, there's just no meaning to any other kind of a comparison.

The problem is that < and > cannot be always used with iterators, because only some kinds of iterators support such operations (namely, random access iterators and the like). On the other hand, comparison operations such as != is always available.

Now, why care about using < and > if != has the same effect and always works?


Suppose you have some generic code:

template <class It>
void foo(It begin, It end)
{
    while (--end != begin)
        apply(*begin);

}

The code will compile for pointers, for example, but it won't for myList.begin().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!