std::erase, std::erase_if(std::vector)
来自cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| 在标头 <vector> 定义
|
||
| (1) | ||
template< class T, class Alloc, class U > constexpr std::vector<T, Alloc>::size_type erase( std::vector<T, Alloc>& c, const U& value ); |
(C++20 起) (C++26 前) |
|
template< class T, class Alloc, class U = T > constexpr std::vector<T, Alloc>::size_type erase( std::vector<T, Alloc>& c, const U& value ); |
(C++26 起) | |
template< class T, class Alloc, class Pred > constexpr std::vector<T, Alloc>::size_type erase_if( std::vector<T, Alloc>& c, Pred pred ); |
(2) | (C++20 起) |
1) 从容器中擦除所有比较等于
value 的元素。等价于
auto it = std::remove(c.begin(), c.end(), value);
auto r = c.end() - it;
c.erase(it, c.end());
return r;
2) 从容器中擦除所有满足
pred 的元素。等价于
auto it = std::remove_if(c.begin(), c.end(), pred);
auto r = c.end() - it;
c.erase(it, c.end());
return r;
参数
| c | - | 要从中擦除的容器 |
| value | - | 要擦除的值 |
| pred | - | 若应该擦除元素则返回 true 的一元谓词。对每个(可为 const 的) |
返回值
被擦除的元素数。
复杂度
线性。
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_algorithm_default_value_type |
202403 |
(C++26) | 算法中的列表初始化 (1) |
示例
运行此代码
#include <complex>
#include <iostream>
#include <numeric>
#include <string_view>
#include <vector>
void println(std::string_view comment, const auto& c)
{
std::cout << comment << '[';
bool first{true};
for (const auto& x : c)
std::cout << (first ? first = false, "" : ", ") << x;
std::cout << "]\n";
}
int main()
{
std::vector<char> cnt(10);
std::iota(cnt.begin(), cnt.end(), '0');
println("起初,cnt = ", cnt);
std::erase(cnt, '3');
println("擦除 '3' 后,cnt = ", cnt);
auto erased = std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; });
println("擦除所有偶数后,cnt = ", cnt);
std::cout << "擦除的偶数:" << erased << '\n';
std::vector<std::complex<double>> nums{{2, 2}, {4, 2}, {4, 8}, {4, 2}};
#ifdef __cpp_lib_algorithm_default_value_type
std::erase(nums, {4, 2});
#else
std::erase(nums, std::complex<double>{4, 2});
#endif
println("After erase {4, 2}, nums = ", nums);
}
输出:
起初,cnt = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
擦除 '3' 后,cnt = [0, 1, 2, 4, 5, 6, 7, 8, 9]
擦除所有偶数后,cnt = [1, 5, 7, 9]
擦除的偶数:5
擦除 {4, 2} 后,nums = [(2,2), (4,8)]
参阅
| 移除满足特定条件的元素 (函数模板) | |
(C++20)(C++20) |
移除满足特定条件的元素 (算法函数对象) |