c++ stl what does base() do

前端 未结 2 612
栀梦
栀梦 2021-02-03 22:33

I have such code :

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

This

相关标签:
2条回答
  • 2021-02-03 22:53

    base() returns the underlying base iterator.

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

    You can learn more about reverse_iterator here.

    0 讨论(0)
  • 2021-02-03 23:05

    base() converts a reverse iterator into the corresponding forward iterator. However, despite its simplicity, this correspondence is not as trivial as one might thing.

    When a reverse iterator points at one element, it dereferences the previous one, so the element it physically points to and the element it logically points to are different. In the following diagram, i is a forward iterator, and ri is a reverse 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 converted to a forward iterator, the resulting iterator will point to element 3, which is the one that gets removed in your example.

    The following small program demonstrates the above behavior:

    #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 live example.

    0 讨论(0)
提交回复
热议问题