命名空间
变体
操作

std::erase, std::erase_if(std::list)

来自 cppreference.cn
< cpp‎ | container‎ | list
 
 
 
 
定义于头文件 <list>
(1)
template< class T, class Alloc, class U >

std::list<T, Alloc>::size_type

    erase( std::list<T, Alloc>& c, const U& value );
(C++20 起)
(C++26 前)
template< class T, class Alloc, class U = T >

std::list<T, Alloc>::size_type

    erase( std::list<T, Alloc>& c, const U& value );
(C++26 起)
template< class T, class Alloc, class Pred >

std::list<T, Alloc>::size_type

    erase_if( std::list<T, Alloc>& c, Pred pred );
(2) (C++20 起)
1) 从容器擦除所有与 value 比较相等的元素。等效于 return c.remove_if([&](const auto& elem) -> bool { return elem == value; });
2) 从容器擦除所有满足谓词 pred 的元素。等效于 return c.remove_if(pred);

内容

[edit] 参数

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

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

[edit] 返回值

已擦除元素的数量。

[edit] 复杂度

线性。

注意

std::list::remove 不同,erase 接受异构类型,且不在调用 == 运算符之前强制转换为容器的值类型。

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

[edit] 示例

#include <complex>
#include <iostream>
#include <numeric>
#include <string_view>
#include <list>
 
void println(std::string_view comment, const auto& c)
{
    std::cout << comment << '[';
    bool first{true};
    for (const auto& x : c)
        std::cout << (first ? first = false, "" : ", ") << x;
    std::cout << "]\n";
}
 
int main()
{
    std::list<char> cnt(10);
    std::iota(cnt.begin(), cnt.end(), '0');
    println("Initially, cnt = ", cnt);
 
    std::erase(cnt, '3');
    println("After erase '3', cnt = ", cnt);
 
    auto erased = std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; });
    println("After erase all even numbers, cnt = ", cnt);
    std::cout << "Erased even numbers: " << erased << '\n';
 
    std::list<std::complex<double>> nums{{2, 2}, {4, 2}, {4, 8}, {4, 2}};
    #ifdef __cpp_lib_algorithm_default_value_type
        std::erase(nums, {4, 2});
    #else
        std::erase(nums, std::complex<double>{4, 2});
    #endif
    println("After erase {4, 2}, nums = ", nums);
}

输出

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
After erase {4, 2}, nums = [(2,2), (4,8)]

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
LWG 4135 C++20 所用 lambda 谓词的返回类型
从谓词参数推导
返回类型为
显式指定为 bool

[edit] 参见

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