Reputation: 21
Once I wrote a line:
while(++itr!=container.end())
{
do something here
}
Even after itr passed end(), the condition is still true. I am puzzled. I thought operator++ should check boundaries. But it seems not. Here is a test program:
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;
}
Is it true that iterator in std c++ do not check past end or before begin() for -- operator?
Upvotes: 2
Views: 98
Reputation: 26
yep.
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
}
}
Upvotes: 0
Reputation: 7603
This is how they work and this is for a performance reason. Iterators are modeled after pointers, pointer don't check for boundaries on increment.
You will get undefined behavior though if you increment past end()
.
Upvotes: 4