Namespaces
Variants

std::erase, std::erase_if(std::basic_string)

来自 zh.cppreference.net

 
 
 
std::basic_string
 
定义于头文件 <string>
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 );
(1) (自 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 。

表达式 pred ( v ) 必须可转换为 bool ,其中参数 v 为(可能为 const 的) CharT 类型,且无论其 值类别 如何,该表达式不得修改 v 。因此,不允许使用 CharT & 作为参数类型 ,也不允许使用 CharT ,除非对于 CharT 类型移动操作等价于复制操作 (C++11 起) 。 ​

返回值

被擦除的元素数量。

复杂度

线性。

注释

功能测试 宏 值 标准 功能
__cpp_lib_algorithm_default_value_type 202403 (C++26) 列表初始化 用于 std::erase

示例

#include <iomanip>
#include <iostream>
#include <string>

int main()
{
    std::string word{"startling"};
    std::cout << "Initially, word = " << std::quoted(word) << '\n';

    std::erase(word, 'l');
    std::cout << "After erase 'l': " << std::quoted(word) << '\n';

    auto erased = std::erase_if(word, [](char x)
    {
        return x == 'a' or x == 'r' or x == 't';
    });

    std::cout << "After erase all 'a', 'r', and 't': " << std::quoted(word) << '\n';
    std::cout << "Erased symbols count: " << erased << '\n';

#if __cpp_lib_algorithm_default_value_type
    std::erase(word, {'g'});
    std::cout << "After erase {'g'}: " << std::quoted(word) << '\n';
#endif
}

可能的输出:

Initially, word = "startling"
After erase 'l', word = "starting"
After erase all 'a', 'r', and 't': "sing"
Erased symbols count: 4
After erase {'g'}: "sin"

参阅

移除字符
(公开成员函数)
移除满足特定判别的元素
(函数模板 & 算法函数对象)
移除满足特定判别的元素
(算法函数对象)