【问题标题】:C++ list iterator reverse_iterator [duplicate]C ++列表迭代器reverse_iterator [重复]
【发布时间】:2012-09-14 11:11:36
【问题描述】:

可能重复:
Why does a push_back on an std::list change a reverse iterator initialized with rbegin?

我得到一段代码如下:

#include <iostream>
#include <list>

int main(){
    std::list<int> l;
    l.push_back(1);
    l.push_back(2);
    std::list<int>::iterator it = l.begin();
    std::cout << *it << std::endl; // 1
    l.push_front(0);
    std::cout << *it << std::endl; // 1
    std::list<int>::reverse_iterator rit = l.rbegin();
    std::cout << *rit << std::endl; // 2
    l.push_back(3);
    std::cout << *rit << std::endl; // 3
}

输出:

1
1
2
3

看起来在我定义了前向迭代器it之后,如果我调用push_front(),it的位置不会改变。但是,在我定义了reverse_iteratorrit之后,如果我调用push_back(),rit的位置就会改变。

这应该被视为不一致吗?对我来说,其中一个移动而另一个保持不变对我来说真的没有任何意义。

提前致谢。 :)

【问题讨论】:

  • 我现在在规范中找不到具体的细节,但这一定是因为'rbegin()'通过'reverse_iterator'适配器返回'end()'。 'reverse_iterator' 变量将位于 'end()' 而 'push_back' 前置值。
  • 当然听起来很合理。 +1
  • @mmodahl 不是 end()。如果它是 end() 他不能取消引用它。无论如何:如果您在创建有问题的集合后修改了迭代器,请不要假设任何关于迭代器的事情。

标签: c++ stdlist


【解决方案1】:

std::list 不会使迭代器无效。正如您在常规迭代器中看到的那样,std::list 上的迭代器即使在列表被修改后也指向同一个元素。

另一方面,反向迭代器被实现为std::reverse_iterator&lt;iterator&gt;,它根据C++ STL documentation,维护一个迭代器,该迭代器指向迭代器返回的元素之前,其中这种情况是列表的结尾。

【讨论】:

  • 为什么投反对票?我做错了什么?这正是另一个答案中所说的。
猜你喜欢
  • 2018-04-26
  • 2017-09-07
  • 2017-07-18
  • 2010-12-19
  • 2023-03-23
  • 2013-02-07
  • 2019-09-29
  • 2023-03-29
  • 2013-08-18
相关资源
最近更新 更多