std::vector<T,Allocator>:: erase
| (1) | ||
|
iterator erase
(
iterator pos
)
;
|
(C++11 前) | |
|
iterator erase
(
const_iterator pos
)
;
|
(C++11 起)
(C++20 起为 constexpr) |
|
| (2) | ||
|
iterator erase
(
iterator first, iterator last
)
;
|
(C++11 前) | |
|
iterator erase
(
const_iterator first, const_iterator last
)
;
|
(C++11 起)
(C++20 起为 constexpr) |
|
从容器中擦除指定元素。
[
first
,
last
)
中的元素。
迭代器(包括
end()
迭代器)以及指向被擦除位置或之后元素的引用均会失效。
迭代器 pos 必须有效且可解引用。因此 end() 迭代器(虽然有效但不可解引用)不能用作 pos 的值。
当迭代器 first 满足 first == last 时,无需进行解引用操作:擦除空范围属于空操作。
目录参数
返回值指向被移除元素之后位置的迭代器。
如果
[
first
,
last
)
是空范围,则返回
last
。
异常处理
除非
复杂度
线性:调用
备注当容器元素需要根据谓词移除时,而不是遍历容器并调用一元 示例
运行此代码
#include <vector> #include <iostream> void print_container(const std::vector<int>& c) { for (int i : c) std::cout << i << ' '; std::cout << '\n'; } int main() { std::vector<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; print_container(c); c.erase(c.begin()); print_container(c); c.erase(c.begin() + 2, c.begin() + 5); print_container(c); // 删除所有偶数 for (std::vector<int>::iterator it = c.begin(); it != c.end();) { if (*it % 2 == 0) it = c.erase(it); else ++it; } print_container(c); } 输出: 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 6 7 8 9 1 7 9 缺陷报告以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
参见
| |||||||||||||||||||||||||||