在 C++ 中,为什么我们不能使用 > 和 < 来比较迭代器?

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

有人问我这个问题,我真的不知道为什么。

如果你有指针int * x;
您可以将指针与 >< 进行比较,因为它代表内存位置,类似于 0x0000 0x0004 0x0008 等。我知道迭代器和指针是不同的,但它们的行为方式非常相似。

例如:

vector<int> myVector;

for(int i = 1; i < 101; i++)
{
    myVector.push_back(i);
}

vector<int>::iterator it = myVector.begin();
while(it != myVector.end()) //Why can't we write it < myVector.end()
{
    cout << *it << endl;
    it++;
}

为什么我们不能在while语句中写< myVector.end()呢? 我知道这与 STL 中的无重载有关。但是,写 &*it < &*myVector.end() 是可行的,因为它获得了显示 0x0004 0x0008 等的内存位置

这是为什么?

std::vector::iterator是一个随机访问迭代器,你当然可以将它们与<>进行比较。

但是,只能使用 ==!= 以外的任何方式比较随机访问迭代器。双向、前向和输入迭代器仅定义 equality/inequality 比较运算符。

例如,

A std::list::iterator 是一个指向 std::list 的某个未指定成员的迭代器。在这种情况下,任何其他类型的比较都没有任何意义。

operator<operator> 只能与 RandomAccessIterator. But operator!= could also be used with InputIterator, ForwardIterator and BidirectionalIterator 一起使用。对于您的示例代码, it != myVector.end()it < myVector.end() 具有相同的效果,但前者更通用,那么该代码也适用于其他迭代器(例如 std::list 或 [=16= 的迭代器) ] 等)。

顺便说一句:您的示例代码可以使用 operator<operator>,因为 std::vector 的迭代器是 RandomAccessIterator

问题是<>不能总是和迭代器一起使用,因为只有某些类型的迭代器支持这样的操作(即随机访问迭代器等)。另一方面,!= 等比较操作总是可用。

既然 <> 如果 != 具有相同的效果并且总是有效,为什么还要关心使用 <>


假设您有一些通用代码:

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

}

例如,代码将针对指针进行编译,但不会针对 myList.begin()