std::erase() 方法
- 自 C++20 起
// prism-push-types:size_type
// (1)
template< class T, class Alloc, class U >
constexpr typename std::vector<T,Alloc>::size_type
erase( std::vector<T,Alloc>& c, U const& value )
// (2)
template< class T, class Alloc, class Pred >
constexpr typename std::vector<T,Alloc>::size_type
erase_if( std::vector<T,Alloc>& c, Pred pred );
- (1) 从容器中删除所有与值相等的元素。等同于
auto it = std::remove(c.begin(), c.end(), value);
auto r = std::distance(it, c.end());
c.erase(it, c.end());
return r; - (2) 从容器中删除所有满足谓词 pred 的元素。等同于
auto it = std::remove_if(c.begin(), c.end(), pred);
auto r = std::distance(it, c.end());
c.erase(it, c.end());
return r;
参数
c
- 要从中删除的容器value
- 要删除的值,用于初始化新元素的值pred
- 一元谓词,如果元素应被删除,则返回true
。对于类型为 (可能是const
)T
的每个参数v
,无论值类别如何,表达式pred(v)
都必须可转换为bool
,并且不得修改v
。因此,不允许使用参数类型T&
(也不允许使用T
,除非对于T
移动等同于复制(自 C++11 起)
)。
返回值
被删除元素的数量。
复杂度
线性。
异常
(无)
示例
Main.cpp
#include <iostream>
#include <numeric>
#include <string_view>
#include <vector>
void print_container(std::string_view comment, const std::vector<char>& c)
{
std::cout << comment;
for (auto x : c) {
std::cout << x << ' ';
}
std::cout << '\n';
}
int main()
{
std::vector<char> cnt(10);
std::iota(cnt.begin(), cnt.end(), '0');
print_container("Init:\n", cnt);
std::erase(cnt, '3');
print_container("Erase '3':\n", cnt);
auto erased = std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; });
print_container("Erase all even numbers:\n", cnt);
std::cout << erased << " even numbers were erased.\n";
}
输出
Init:
0 1 2 3 4 5 6 7 8 9
Erase '3':
0 1 2 4 5 6 7 8 9
Erase all even numbers:
1 5 7 9
5 even numbers were erased.