c ++ stl base()做什么 [英] c++ stl what does base() do

查看:66
本文介绍了c ++ stl base()做什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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

此代码在首次检测到2后从向量v中删除第一个元素(向量中的剩余部分为:0 1 2 4)..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?

推荐答案

base()将反向迭代器转换为相应的正向迭代器.但是,尽管它很简单,但这种对应并不像一件事情那么琐碎.

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

当反向迭代器指向一个元素时,它将取消引用前一个元素,因此物理上指向的元素和逻辑上指向的元素是不同的.在下图中, i 是正向迭代器,而 ri 是根据 i 构造的反向迭代器:

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

因此,如果 ri 在逻辑上指向元素 2 ,则其物理上指向元素 3 .因此,当转换为正向迭代器时,生成的迭代器将指向元素 3 ,这是在您的示例中删除的元素.

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
}

这是一个 实时示例 .

这篇关于c ++ stl base()做什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆