C ++ stl, which makes base () do

I have a code like this:

vector <int> v; for (int i=0; i<5; i++) v.push_back(i); v.erase(find(v.rbegin(), v.rend(),2).base()); 

This code removes the first element from vector v after the first detection of 2 (in the vector remain: 0 1 2 4). What does .base () do here?

+13
c ++ vector erase
May 17 '13 at 12:27
source share
2 answers

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 .

+22
May 17 '13 at 12:32
source share

base() returns the base iterator of the base.

The base iterator refers to the element that is next to the element currently indicates reverse_iterator . That is, std::reverse_iterator(it).base() == std::next(it) .

Read more about reverse_iterator here .

enter image description here

+8
May 17 '13 at 12:31
source share



All Articles