命名空间
变体
操作

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;

目录

[编辑] 参数

c - 要从中删除元素的容器
value - 要删除的值
pred - 一元谓词,如果元素应被删除,则返回 ​true

表达式 pred(v) 对于类型为(可能 const)CharT 的每个参数 v,必须可转换为 bool,无论 值类别如何,并且不得修改 v。因此,不允许参数类型为 CharT&,除非对于 CharT 移动等效于复制,否则也不允许 CharT(C++11 起)

[编辑] 返回值

被删除元素的数量。

[编辑] 复杂度

线性。

注意

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

[编辑] 示例

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

[编辑] 参阅

移除满足特定标准的元素
(函数模板) [编辑]
移除满足特定标准的元素
(算法函数对象)[编辑]
English 日本語 中文(简体) 中文(繁體)