Can an STL map iterator go out of bounds in increments?

For associative containers, can the ++ operator send an iterator to the end of the collection?

Example:

map<UINT32, UINT32> new_map; new_map[0] = 0; new_map[1] = 1; map<UINT32, UINT32> new_iter = new_map.begin(); ++new_iter; ++new_iter; ++new_iter; ++new_iter; ++new_iter; ++new_iter; ++new_iter; 

At the end of this, new_iter == new_map.end (), or does it fall into the big unknown?

Note. I know this is messed up, not a way to do something. I am working on corporate WTF code.

+7
c ++ stl
source share
3 answers

If you increment the final iterator, the result is undefined behavior. This way, he can stay at the end or come out of the end, or send a link to goats by email to your grandmother.

See also: What if I increment the iterator by 2 when it points to the last element of the vector?

+26
source share

A precondition for the ++ operator for a forward iterator is that the iterator is dereferenced. This means that it cannot get past the end of the map, so your code gives undefined behavior. This is described in section 24.1.3 of the C ++ Standard.

+11
source share

As others noted, incrementing the final iterator causes undefined behavior, however it is worth noting that Visual Studio 2008 will display a debug statement at runtime (because iterators are checked ) if you do this.

+5
source share

All Articles