STL reverse iterator and its base()

Question:

I have such code :

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 deletes the first element from vector v after first detected 2 (in vector remain: 0 1 2 4). What does .base() do here?


Answer:

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, iis 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
}
事实上,ri.base()总是逻辑指针的后面一个,所以这个例子里面,是2的后一个元素,3.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值