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

 
 
 
 
定义于头文件 <forward_list>
template< class T, class Alloc, class U >

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

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

typename 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([&](auto& elem) { return elem == value; });
2) 从容器中擦除所有满足 pred 的元素。等价于 return c.remove_if(pred);

参数

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

对每个(可为 const 的) T 类型参数 v ,表达式 pred(v) 必须可转换为 bool ,无关乎值类别,而且必须不修改 v 。从而不允许 T& 类型参数,亦不允许 T ,除非对 T 而言移动等价于复制 (C++11 起)。 ​

返回值

被擦除的元素数。

复杂度

线性。

示例

#include <iostream>
#include <numeric>
#include <forward_list>
 
void print_container(const std::forward_list<char>& c)
{
    for (auto x : c) {
        std::cout << x << ' ';
    }
    std::cout << '\n';
}
 
int main()
{
    std::forward_list<char> cnt(10);
    std::iota(cnt.begin(), cnt.end(), '0');
 
    std::cout << "Init:\n";
    print_container(cnt);
 
    auto erased = std::erase(cnt, '3');
    std::cout << "Erase \'3\':\n";
    print_container(cnt);
 
    std::erase_if(cnt, [](char x) { return (x - '0') % 2 == 0; });
    std::cout << "Erase all even numbers:\n";
    print_container(cnt);
    std::cout << "In all " << erased << " even numbers were erased.\n";
}

输出:

Init:
0 1 2 3 4 5 6 7 8 9 
Erase '3':
0 1 2 4 5 6 7 8 9 
Erase all even numbers:
1 3 7 9
In all 5 even numbers were erased.

注解

不同于 std::forward_list::removeerase 接受异种类型并且不强制在调用 == 运算符前转换到容器的值类型。

参阅

移除满足特定判别标准的元素
(函数模板)
移除满足特定标准的元素
(公开成员函数)