I'm trying to reverse iterate through a std::map, following this code: http://www.cplusplus.com/reference/stl/map/rend/ It says:
rend() returns a reverse iterator referring to the element right before the first element in the map container, which is considered its reverse end.
Notice that rend does not refer to the same element as begin, but to the element right before it.
map<float,int> m;
m.insert(pair<float,int>(.1,0));
m.insert(pair<float,int>(.4,5));
map<float,int>::reverse_iterator rend=m.rend();
map<float,int>::iterator begin=m.begin();
When I run this, both rend and begin point to the first element of m, (.1,0), when obviously it shouldn't, given the Notice above. I feel like there's some very obvious mistake I'm making, but I can't figure out what it could be.
(C++,MSVC2010)
I believe the point you are missing is that if you inspect the values using a debugger, the values returned by rend() and begin() will contain the same value. However, the operator* members of the iterator types will still give you access to different objects.
Technical details: The value returned by rend() cannot point before begin(), because that is not valid. So it was decided that rend() should contain the value of begin() and all other reverse iterators be shifted one position further. The operator* compensates for this and accesses the correct element anyway.
First paragraph of 24.5.1 Reverse iterators says:
Class template reverse_iterator is an iterator adaptor that iterates from the end of the sequence defined by its underlying iterator to the beginning of that sequence. The fundamental relation between a reverse iterator and its corresponding iterator i is established by the identity:
&*(reverse_iterator(i)) == &*(i - 1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With