一旦我写了一句话:
while(++itr!=container.end())
{
do something here
}
即使在它通过end()之后,条件仍然是正确的。我很困惑。我认为operator ++应该检查边界。但似乎没有。这是一个测试程序:
int main()
{
vector<int> x;
vector<string> y;
x.push_back(10);
y.push_back("test");
auto itr = x.end();
assert(itr == x.end());
// this line makes itr past end
++itr;
// this line is true
assert(itr != x.end());
// this line doesn't report any address issue or segment fault
cout << *itr << endl;
auto itry = y.end();
assert(itry == y.end());
++itry;
// no error report
assert(itry != y.end());
// report segment fault
cout << *itry << endl;
return 0;
}
std c ++中的迭代器是不是检查过去的结尾或者在begin()之前检查 - 运算符?
答案 0 :(得分:4)
这是他们的工作方式,这是出于性能原因。迭代器是在指针之后建模的,指针不会在增量时检查边界。
如果增量超过end()
,您将获得未定义的行为。
答案 1 :(得分:0)
是的。
while(++itr!=container.end())
{
do something here
}
if itr==end() ,++itr can be anything!
so,you must write :
if(it != xxx.end())
{
while(++it != xxx.end())
{
do sth
}
}