命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
常量
非成员函数
erase(std::basic_string)erase_if(std::basic_string)
(C++20)(C++20)
I/O
比较
(直到 C++20)(直到 C++20)(直到 C++20)(直到 C++20)(直到 C++20)(C++20)
数值转换
(C++11)(C++11)(C++11)
(C++11)(C++11) 
(C++11)(C++11)(C++11)
(C++11)
(C++11)
字面量
辅助类
推导指引 (C++17)
 
定义于头文件 <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;

目录

[edit] 参数

c - 从中擦除元素的容器
value - 要移除的值
pred - 一元谓词,若元素应被擦除则返回 true

表达式 pred(v) 必须可转换为 bool ,对每个 v 的实参,类型为(可能为 const ) CharT ,忽略值类别,且不得修改 v 。 故不允许 CharT& 的形参类型,亦不允许 CharT ,除非对 CharT 移动等价于复制(C++11 起) 。 ​

[edit] 返回值

被擦除元素的数量。

[edit] 复杂度

线性。

注解

特性测试 Std 特性
__cpp_lib_algorithm_default_value_type 202403 (C++26) 列表初始化 算法 (1)

[edit] 示例

#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"

[edit] 参见

移除满足特定标准的元素
(函数模板) [编辑]
移除满足特定标准的元素
(算法函数对象)[编辑]