std::erase, std::erase_if (std::basic_string)
来自cppreference.com
< cpp | string | basic string
在标头 <string> 定义
|
||
template< class CharT, class Traits, class Alloc, class U > constexpr typename std::basic_string<CharT, Traits, Alloc>::size_type |
(1) | (C++20 起) |
template< class CharT, class Traits, class Alloc, class Pred > constexpr typename std::basic_string<CharT, Traits, Alloc>::size_type |
(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 的) |
返回值
被擦除的元素数。
复杂度
线性。
示例
运行此代码
#include <iostream> #include <numeric> #include <string_view> #include <string> void print_container(std::string_view comment, const std::string& c) { std::cout << comment << "{ "; for (auto x : c) { std::cout << x << ' '; } std::cout << "}\n"; } int main() { std::string cnt(10, ' '); std::iota(cnt.begin(), cnt.end(), '0'); print_container("Initially, cnt = ", cnt); std::erase(cnt, '3'); print_container("After erase '3', cnt = ", cnt); auto erased = std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; }); print_container("After erase all even numbers, cnt = ", cnt); std::cout << "Erased even numbers: " << erased << '\n'; }
输出:
Initially, cnt = { 0 1 2 3 4 5 6 7 8 9 } After erase '3', cnt = { 0 1 2 4 5 6 7 8 9 } After erase all even numbers, cnt = { 1 5 7 9 } Erased even numbers: 5
参阅
移除满足特定判别标准的元素 (函数模板) |