在C ++中,为什么不能使用>比较迭代器?和< ;? [英] In C++ why can't we compare iterators using > and <?
问题描述
有人问我这个问题,我真的不知道为什么.
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 , BidirectionalIterator .对于您的示例代码,it != myVector.end()
和it < myVector.end()
具有相同的效果,但是前者更为通用,因此该代码还可以与其他迭代器(例如std::list
或std::map
的迭代器等)一起使用.
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 ++中,为什么不能使用>比较迭代器?和< ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!