假设我们有这段代码:
set<int> s;
set<int>::iterator it = s.find(val);
s.erase(it);
正如 cplusplus.com 所说,如果 int val
set<int> s
中不存在然后,s.find(val)
将返回 set::end
.
现在我的问题是,如果我们通过 set::end
会发生什么?到 set::erase()
?
是否可以接收到类似segmentation fault
的信号或 aborted
并得到一个运行时错误?或者这种特殊情况在set
中得到处理?
最佳答案
在 C++03 中,采用单个迭代器的 std::set::erase()
的行为在表 69 中定义,其中有以下假设(添加了突出显示) :
In Table 69, X is an associative container class, a is a value of X, a_uniq is a value of X when X supports unique keys, and a_eq is a value of X when X supports multiple keys, i and j satisfy input iterator requirements and refer to elements of value_type, [i, j) is a valid range, p is a valid iterator to a, q is a valid dereferenceable iterator to a, [q1, q2) is a valid range in a, t is a value of X::value_type, k is a value of X::key_type and c is a value of type X::key_compare.
表 69 说明了 erase()
函数:
a.erase(q)
- erases the element pointed to byq
换句话说,迭代器必须是可解引用的。如果不是,则为未定义行为,因为不满足前提条件。
没有关于库以任何特定方式运行的 promise 。某些库(例如 MSVC 的)可以在某些配置中包含迭代器调试。例如,当使用调试配置在 VS 2012 中运行时,您将看到以下内容:
---------------------------
Microsoft Visual C++ Runtime Library
---------------------------
Debug Assertion Failed!
Program: C:\Windows\system32\MSVCP110D.dll
File: c:\program files (x86)\microsoft visual studio 11.0\vc\include\xtree
Line: 1326
Expression: map/set erase iterator outside range
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
---------------------------
Abort Retry Ignore
---------------------------
关于c++ - set::erase() 如何将 set::end 作为其参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15347386/