std::erase, std::erase_if (std::basic_string)
来自cppreference.com
< cpp | string | basic string
定义于头文件 <string>
|
||
template< ..., class U > constexpr typename std::basic_string<...>::size_type |
(1) | (C++20 起) |
template< ..., class Pred > constexpr typename std::basic_string<...>::size_type |
(2) | (C++20 起) |
1) 从容器中擦除所有比较等于
value
的元素。等价于
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 的) |
返回值
被擦除的元素数。
复杂度
线性。
示例
运行此代码
#include <iostream> #include <numeric> #include <string> void print_container(const std::string& c) { for (auto x : c) { std::cout << x << ' '; } std::cout << '\n'; } int main() { std::string cnt(10, ' '); std::iota(cnt.begin(), cnt.end(), '0'); std::cout << "Init:\n"; print_container(cnt); auto erased = std::erase(cnt, '3'); std::cout << "Erase \'3\':\n"; print_container(cnt); std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; }); std::cout << "Erase all even numbers:\n"; print_container(cnt); std::cout << "In all " << 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 In all 5 even numbers were erased.
参阅
移除满足特定判别标准的元素 (函数模板) |