迭代器值与转换后的反向迭代器值不同 [英] Iterator value differs from reverse iterator value after conversion

查看:165
本文介绍了迭代器值与转换后的反向迭代器值不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

int main()
{
    vector<int> v;

    for(int i = 0; i < 10; ++i)
        v.push_back(i);

    auto it = v.begin() + 3;

    cout << "Iterator: " << *it << endl;

    vector<int>::reverse_iterator revIt(it);

    cout << "Reverse iterator: " << *revIt << endl;

}

运行此代码后,我得到以下输出:

After running this code I get the following output:

Iterator: 3
Reverse iterator: 2

有人可以解释为什么2个值不同吗?

Could someone explain why the 2 values differ ?

推荐答案

反向迭代器的对应由于 rbegin()的方式,'到 base 迭代器的偏移量为一个元素rend()必须使用有效的基本迭代器来表示( end() begin()分别)。例如, rend()不能由容器的 begin()迭代器之前指向的交互器表示,虽然这是它在逻辑上代表的东西。所以 rend()的'基础迭代器'是 begin()。因此, rbegin()的基本迭代器变为 end()
反向迭代器在取消引用时自动调整该偏移量(使用 * - > 运营商)。

Reverse iterators 'correspond' to a base iterator with an offset of one element because of how rbegin() and rend() have to be represented using base iterators that are valid (end() and begin() respectively). For example, rend() cannot be represented by an interator that 'points' before the container's begin() iterator, although that's what it logically represents. So rend()'s 'base iterator' is begin(). Therefore, rbegin()'s base iterator becomes end(). A reverse iterator automatically adjusts for that offset when it is dereferenced (using the * or -> operators).

旧的 Scott Meyers的文章详细解释了这种关系以及一张漂亮的图片:

An old article by Scott Meyers explains the relationship in detail along with a nice picture:


准则3:了解如何使用reverse_iterator的基础迭代器

在reverse_iterator上调用基本成员函数会产生
对应迭代器,但这并不是很清楚这意味着什么。
例如,看看这个代码,它将数字1-5放在
a向量中,设置reverse_iterator指向3,并将
迭代器设置为reverse_iterator的基数:

Invoking the base member function on a reverse_iterator yields the "corresponding" iterator, but it’s not really clear what that means. As an example, take a look at this code, which puts the numbers 1-5 in a vector, sets a reverse_iterator to point to the 3, and sets an iterator to the reverse_iterator’s base:

vector<int> v;

// put 1-5 in the vector
for (int i = 1; i <= 5; ++i) {
  v.push_back(i);
}

// make ri point to the 3
vector<int>::reverse_iterator ri =
  find(v.rbegin(), v.rend(), 3);

// make i the same as ri's base
vector<int>::iterator i(ri.base());

执行此代码后,可以认为事情看起来像
这样:

After executing this code, things can be thought of as looking like this:

这张图很不错,显示了
reverse_iterator的特征偏移量及其相应的基础迭代器,它模仿了rbegin()和rend()的
偏移量。 begin()和end(),但
它不会告诉你需要知道的一切。特别是,
没有解释如何使用i来执行你想要在ri上执行
的操作。

This picture is nice, displaying the characteristic offset of a reverse_iterator and its corresponding base iterator that mimics the offset of rbegin() and rend() with respect to begin() and end(), but it doesn’t tell you everything you need to know. In particular, it doesn’t explain how to use i to perform operations you’d like to perform on ri.

这篇关于迭代器值与转换后的反向迭代器值不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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