c++ stl what does base() do

风流意气都作罢 提交于 2019-12-03 04:55:44

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!