命名空间
变体
操作

std::erase, std::erase_if(std::inplace_vector)

来自 cppreference.cn
 
 
 
 
在头文件 <inplace_vector> 中定义
template< class T, std::size_t N, class U = T >

constexpr typename std::inplace_vector<T, N>::size_type

    erase( std::inplace_vector<T, N>& c, const U& value );
(1) (C++26 起)
template< class T, std::size_t N, class Pred >

constexpr typename std::inplace_vector<T, N>::size_type

    erase_if( std::inplace_vector<T, N>& c, Pred pred );
(2) (C++26 起)
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

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

[编辑] 返回值

被删除元素的数量。

[编辑] 复杂度

线性。

[编辑] 示例

#include <cassert>
#include <complex>
#include <inplace_vector>
#include <numeric>
#include <print>
 
int main()
{
    std::inplace_vector<int, 10> v(10, 0);
    std::ranges::iota(v, 0);
    std::println("Initially, v = {}", v);
 
    auto erased = std::erase(v, 3);
    std::println("After erase(v, 3), v = {}", v);
    assert(erased == 1);
 
    erased = std::erase_if(v, [](int x) { return x % 2 == 0; });
    std::println("After erasing all even numbers, v = {}", v);
    std::println("Erased even numbers: {}", erased);
 
    std::inplace_vector<std::complex<double>> nums{{2, 2}, {4, 2}, {4, 8}, {4, 2}};
    std::erase(nums, {4, 2}); // since U = T, the value type can be ommited
    std::println("After erase {4, 2}, nums = {}", nums);
}

输出

Initially, v = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After erase(v, 3), v = [0, 1, 2, 4, 5, 6, 7, 8, 9]
After erasing all even numbers, v = [1, 5, 7, 9]
Erased even numbers: 5
After erase {4, 2}, nums = [(2,2), (4,8)]

[编辑] 参阅

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