std::erase, std::erase_if(std::basic_string)
来自cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| 在标头 <string> 定义
|
||
| (1) | ||
template< class CharT, class Traits, class Alloc, class U > constexpr std::basic_string<CharT, Traits, Alloc>::size_type erase( std::basic_string<CharT, Traits, Alloc>& c, const U& value ); |
(C++20 起) (C++26 前) |
|
template< class CharT, class Traits, class Alloc, class U = CharT > constexpr std::basic_string<CharT, Traits, Alloc>::size_type erase( std::basic_string<CharT, Traits, Alloc>& c, const U& value ); |
(C++26 起) | |
template< class CharT, class Traits, class Alloc, class Pred > constexpr std::basic_string<CharT, Traits, Alloc>::size_type erase_if( std::basic_string<CharT, Traits, 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 <iomanip>
#include <iostream>
#include <string>
int main()
{
std::string word{"startling"};
std::cout << "起初,word = " << std::quoted(word) << '\n';
std::erase(word, 'l');
std::cout << "擦除 'l' 后:" << std::quoted(word) << '\n';
auto erased = std::erase_if(word, [](char x)
{
return x == 'a' or x == 'r' or x == 't';
});
std::cout << "擦除全部 'a'、'r' 和 't' 后:" << std::quoted(word) << '\n';
std::cout << "被擦除符号计数:" << erased << '\n';
#if __cpp_lib_algorithm_default_value_type
std::erase(word, {'g'});
std::cout << "擦除 {'g'} 后: " << std::quoted(word) << '\n';
#endif
}
输出:
起初,word = "startling"
擦除 'l' 后:"starting"
擦除全部 'a'、'r' 和 't' 后:"sing"
被擦除符号计数:4
擦除 {'g'} 后: "sin"
参阅
| 移除满足特定条件的元素 (函数模板) | |
(C++20)(C++20) |
移除满足特定条件的元素 (算法函数对象) |