命名空间
变体
操作

std::erase, std::erase_if(std::forward_list)

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

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

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

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

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

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

    erase_if( std::forward_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);

目录

[编辑] 参数

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

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

[编辑] 返回值

被移除元素的数量。

[编辑] 复杂度

线性。

注解

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

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

[编辑] 示例

#include <complex>
#include <iostream>
#include <numeric>
#include <string_view>
#include <forward_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::forward_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::forward_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

[编辑] 参见

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