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

标签 c++

我有这个代码:

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

相关文章:

c++ - 在 QTableView 的图标下方而不是右侧设置文本?

c++ - 使用 RAW_SOCKET 读取 TCP header 并管理 TCP 连接

c# - 由非托管 (C++) COM 服务器实例化的托管 (C#) 控件在 Windows 更新后损坏

c++ - 由2个SQL连接创建的死锁,每个使用事务,不同的表,两个表之间的外键约束

c++ - Boost Asio 始终返回 0.0.0.0 IP

c++ - ASIO 试图引用一个已删除的函数

c++ - Qt 应用程序中的奇怪错误

c++ - 如何防止 QTextDocument block 或框架中的分页符?

c++ - 从函数返回的 void* 指针 - 堆损坏

c++ - boost::asio UDP 广播