gpt4 book ai didi

c++ - std::list.unique() 应该使迭代器无效?

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:09 25 4
gpt4 key购买 nike

我有这个代码:

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com