c++ - 删除 `end()` 的 `std::list` 的行为是什么?

标签 c++ stl iterator

在使用 std::find 找到一个元素后,我需要从 std::list 中删除它。使用列表的 end() 调用 std::list::erase 的行为是什么?我的情况是这样的:

std::list<T> mylist;
T value;
std::list::iterator it = std::find(mylist.begin(), mylist.end(), value);
std::list::iterator next = mylist.erase(it);

cplusplus.com说:

If position (or the range) is valid, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.

但我不知道 end() 是否被认为是有效的。

最佳答案

该站点使用了含糊(并且可以说是不正确的)术语“有效”,但库规范 (C++11 23.2.3) 使用了更具体的术语“可解引用”——这意味着迭代器必须引用一个对象。尾后迭代器不可取消引用,因此删除它会产生未定义的行为。

关于c++ - 删除 `end()` 的 `std::list` 的行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15116676/

相关文章:

c++ - 在 C++ 中有选择地读取格式化的数据文件

java - Java 中的树迭代器

C++ 列表迭代器算法

c++ - Opencv L*a*b* 到 RGB 转换产生灰度输出

c++ - 在 boost 图库中为深度优先搜索提供颜色图时遇到问题

c++ - 映射/设置迭代器不可解除(C++)-调试声明失败?

c++ - MSVC++ 17 std::copy 期望自定义迭代器为 "operator -"

c++ - 在 STL 列表中输出一个元组

c++ - 学习C++,下一步是什么?还有什么是推荐的编译器?

c++ - int/string[] 的集合,每次插入一行代码