读书人

为啥不同的vector他们的迭代器不能相

发布时间: 2013-02-17 10:44:46 作者: rapoo

为什么不同的vector,他们的迭代器不能相互比较呢?
据我所知,vector的迭代器类型就是指针啊,按道理两个指针是可以相互比较大小的啊(虽然有时候没任何意义),但是怎么两个不同的vector(类型一样),他们的迭代器一比较就出错呢?比如下面的代码

#include<iostream>
#include<vector>
using namespace std;

int main()
{
int a[2]={1,2};
vector<int>::iterator it1,it2;
vector<int> ivec1(a,a+2);
vector<int> ivec2(a,a+2);
it1=ivec1.begin();
it2=ivec2.begin();
bool b=it1<it2;
system("pause");
return 0;
}
vector
[解决办法]

// vector
bool operator<(const _Myt& _Right) const
{// test if this < _Right

#if _HAS_ITERATOR_DEBUGGING
_Compat(_Right);
#else
_SCL_SECURE_VALIDATE(this->_Has_container() && this->_Same_container(_Right));
#endif /* _HAS_ITERATOR_DEBUGGING */

return (_Myptr < _Right._Myptr);
}

#if _HAS_ITERATOR_DEBUGGING
void _Compat(const _Myt& _Right) const
{// test for compatible iterator pair
if (this->_Mycont == 0
[解决办法]
this->_Mycont != _Right._Mycont)
////判断两个向量的型类是否一致
{
_DEBUG_ERROR("vector iterators incompatible");
_SCL_SECURE_INVALID_ARGUMENT;
}
}
#endif /* _HAS_ITERATOR_DEBUGGING */


[解决办法]
引用:
你不要认为所有的迭代器都是某个类的对象,至少vector的迭代器不是,他就是一个赤裸裸的原型指针


我不知道你看过几个stl的实做,但是有一件事情你得知道
stl是标准,不代表任何一个库的实做
所以不同编译器的stl,性能的表现可以差很远
早期,这种现象尤其严重(看看vc6.0自带的和sgi stl的性能差距)

effective stl item 16
vector的iterator一般上是pointer
但他们并非总是pointer

[解决办法]
iterator的比较操作符是有限制的。

9.2. Iterators and Iterator Ranges

Table 9.3. Common Iterator Operations
iter1 == iter2
iter1 != iter2
Compare two iterators for equality (inequality). Two iterators are equal if they refer to the same element of the same container or if they are the off-the-end iterator (Section 3.4, p. 97) for the same container.


Table 9.4. Operations Supported by vector and deque Iterators

>, >=, <, <=
Relational operators on iterators. One iterator is less than another if it refers to an element whose position in the container is ahead of the one referred to by the other iterator. The iterators must refer to elements in the same container or one past the end of the container.



Supported only for vector and deque.

读书人网 >C++

热点推荐