tags:

views:

240

answers:

3

For associative containers, can the ++ operator send an iterator past the end of a 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, does new_iter == new_map.end(), or does it end up in the great unknown?

Note: I know this is messed up and not the way to do things. I'm working around some WTF corporate code.

+15  A: 

If you increment the end iterator, the result is undefined behavior. So, it could remain end, or go off the end, or email your grandmother a link to goatse.

See also: http://stackoverflow.com/questions/1057724/what-if-i-increment-an-iterator-by-2-when-it-points-onto-the-last-element-of-a-ve

Tyler McHenry
You forgot the Nasty Nasal Demons. `:)`
sbi
+9  A: 

The precondition on the ++ operator for a forward iterator is that the iterator is dereferenceable. This implies it cannot be past the end of the map, so your code gives undefined behaviour. This is described in section 24.1.3 of the C++ Standard.

anon
+5  A: 

As others have pointed out, incrementing the end iterator causes undefined behaviour, however it's worth noting that Visual Studio 2008 will throw a debug assertion at runtime (due to its checked iterators) if you do this.

Alan