【发布时间】: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() 他不能取消引用它。无论如何:如果您在创建有问题的集合后修改了迭代器,请不要假设任何关于迭代器的事情。