Namespaces
Variants

std::list<T,Allocator>:: erase

From cppreference.net

(1)
iterator erase ( iterator pos ) ;
(C++11 前)
iterator erase ( const_iterator pos ) ;
(C++11 起)
(C++26 起为 constexpr)
(2)
iterator erase ( iterator first, iterator last ) ;
(C++11 前)
iterator erase ( const_iterator first, const_iterator last ) ;
(C++11 起)
(C++26 起为 constexpr)

从容器中擦除指定元素。

1) 移除位于 pos 处的元素。
2) 移除范围 [ first , last ) 中的元素。

被擦除元素的引用和迭代器将失效。其他引用和迭代器不受影响。

迭代器 pos 必须有效且可解引用。因此 end() 迭代器(虽然有效但不可解引用)不能用作 pos 的值。

当迭代器 first 满足 first == last 时,无需进行解引用操作:擦除空范围属于空操作。

目录

参数

pos - 指向待移除元素的迭代器
first, last - 定义待移除元素范围的迭代器对

返回值

指向被移除元素之后位置的迭代器。

1) 如果 pos 指向最后一个元素,则返回 end() 迭代器。
2) 若移除前 last == end ( ) ,则返回更新后的 end() 迭代器。
如果 [ first , last ) 是空范围,则返回 last

复杂度

1) 常量。
2) first last 之间的距离成线性关系。

注释

当需要基于谓词擦除容器元素时,通常不采用遍历容器并调用一元 erase 的方式,而是使用迭代器范围重载配合 std::remove()/std::remove_if() 来最小化剩余(未删除)元素的移动次数——这就是擦除-删除惯用法。 std::erase_if() 已取代擦除-删除惯用法。 (C++20 起)

示例

#include <list>
#include <iostream>
#include <iterator>
void print_container(const std::list<int>& c)
{
    for (int i : c)
        std::cout << i << ' ';
    std::cout << '\n';
}
int main()
{
    std::list<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    print_container(c);
    c.erase(c.begin());
    print_container(c);
    std::list<int>::iterator range_begin = c.begin();
    std::list<int>::iterator range_end = c.begin();
    std::advance(range_begin, 2);
    std::advance(range_end, 5);
    c.erase(range_begin, range_end);
    print_container(c);
    // 删除所有偶数
    for (std::list<int>::iterator it = c.begin(); it != c.end();)
    {
        if (*it % 2 == 0)
            it = c.erase(it);
        else
            ++it;
    }
    print_container(c);
}

输出:

0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
1 2 6 7 8 9
1 7 9

缺陷报告

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

缺陷报告 应用于 发布时行为 正确行为
LWG 151 C++98 first 被要求必须可解引用,这
使得清空一个空 list 的行为未定义

first == last 时不作要求

参见

擦除所有满足特定条件的元素
(函数模板)
清空内容
(公开成员函数)