在C ++中,为什么不能使用>比较迭代器?和&lt ;? [英] In C++ why can't we compare iterators using > and <?

查看:93
本文介绍了在C ++中,为什么不能使用>比较迭代器?和&lt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been asked this question which I do not really know why.

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

If you have a pointer int * x;
You can compare pointers with > and < because it stands for the memory location something like 0x0000 0x0004 0x0008, etc. I know iterators and pointers are different, but they act in a very similar way.

例如:

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等的内存位置.

Why can't we write it < myVector.end() in the while statement? I know it has to do with no overloading in STL. However, writing &*it < &*myVector.end() works because it gets the memory location which reveals say 0x0004 0x0008, etc.

这是为什么?

推荐答案

operator<operator>仅可与 InputIterator

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

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

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

这篇关于在C ++中,为什么不能使用&gt;比较迭代器?和&lt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆