base() converts the inverse iterator to the corresponding imperial iterator. However, despite its simplicity, this correspondence is not as trivial as it could be.
When a reverse iterator points to one element, it casts the previous one, so the element that it physically points to and the element that it logically points to are different. In the following diagram, i is the direct iterator, and ri is the inverse iterator constructed from i :
i, *i | - 0 1 2 3 4 - | | *ri ri
So, if ri logically points to element 2 , it physically points to element 3 . Therefore, when converting to a forward iterator, the resulting iterator will point to element 3 , which will be deleted in your example.
The following small program demonstrates the behavior described above:
#include <iostream> #include <vector> #include <iterator> #include <algorithm> int main(int argc, char *argv[]) { std::vector<int> v { 0, 1, 2, 3, 4 }; auto i = find(begin(v), end(v), 2); std::cout << *i << std::endl; // PRINTS 2 std::reverse_iterator<decltype(i)> ri(i); std::cout << *ri << std::endl; // PRINTS 1 }
Here is a living example .
Andy Prowl May 17 '13 at 12:32 2013-05-17 12:32
source share