我有这个代码:
#include <iostream>
#include <list>
int main()
{
typedef std::list<int> list;
int i0t[5]={-1, 2, 3, 3, 5};
list list_1(i0t, i0t+5);
list::reverse_iterator ri0 = ++list_1.rbegin();
list_1.unique();
list_1.remove(3);
int val = *ri0; // why is this valid ?
std::cout << "val = " << val << "\n";
return 0;
}
我的直觉是 ri0 迭代器将在
之后变得无效
list_1.unique();
list_1.remove(3);
使用带有 _HAS_ITERATOR_DEBUGGING=1 的 MS VS2005 调试配置
然而,我认为“迭代器调试”没有捕获这一点。对吗?
谢谢。
最佳答案
My intuition was that ri0 iterator would become invalid
是的,会的。根据第 23.3.5.5 条
void remove(const T& value)
void unique()
[...] Invalidates only the iterators and references to the erased elements.
因此,您的程序的行为是未定义的。
关于c++ - std::list.unique() 应该使迭代器无效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751734/