CppDS.com

C++ 98 11 14 17 20 手册

std::erase, std::erase_if (std::vector)

来自cppreference.com
< cpp‎ | container‎ | vector

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

constexpr typename std::vector<T,Alloc>::size_type

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

constexpr typename std::vector<T,Alloc>::size_type

    erase_if(std::vector<T,Alloc>& c, Pred pred);
(2) (C++20 起)
1) 从容器中擦除所有比较等于 value 的元素。等价于
auto it = std::remove(c.begin(), c.end(), value);
auto r = std::distance(it, c.end());
c.erase(it, c.end());
return r;
2) 从容器中擦除所有满足 pred 的元素。等价于
auto it = std::remove_if(c.begin(), c.end(), pred);
auto r = std::distance(it, c.end());
c.erase(it, c.end());
return r;

参数

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

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

返回值

被擦除的元素数。

复杂度

线性。

示例

#include <iostream>
#include <numeric>
#include <vector>
 
void print_container(const std::vector<char>& c)
{
    for (auto x : c) {
        std::cout << x << ' ';
    }
    std::cout << '\n';
}
 
int main()
{
    std::vector<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.


参阅

移除满足特定判别标准的元素
(函数模板)
关闭