std::map<Key,T,Compare,Allocator>::erase

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

(1)
void erase( iterator pos );
(C++11 前)
iterator erase( iterator pos );
(C++11 起)
iterator erase( const_iterator pos );
(C++11 起)
(2)
void erase( iterator first, iterator last );
(C++11 前)
iterator erase( const_iterator first, const_iterator last );
(C++11 起)
size_type erase( const key_type& key );
(3)
template< class K >
size_type erase( K&& x );
(4) (C++23 起)

从容器移除指定的元素。

1) 移除位于 pos 的元素。
2) 移除范围 [first; last) 中的元素,它必须是 *this 中的合法范围。
3) 移除键等价于 key 的元素(若存在一个)。
4) 移除键比较等价于值 x 的元素(若存在一个)。此重载仅若有限定标识 Compare::is_transparent 合法并指代类型,且 iteratorconst_iterator 均不可从 K 隐式转换才参与重载决议。它允许无需构造 Key 的实例就调用此函数。

指向被擦除元素的引用和迭代器被非法化。其他引用和迭代器不受影响。

迭代器 pos 必须合法且可解引用。从而 end() 迭代器(合法,但不可解引用)不能用作 pos 所用的值。

参数

pos - 指向要移除的元素的迭代器
first, last - 要移除的元素范围
key - 要移除的元素键值
x - 任何能与键通透比较的类型的值,指代要移除的元素

返回值

1-2) (无) (C++11 前)后随最后被移除的元素的迭代器。 (C++11 起)
3,4) 被移除的元素数。

异常

1,2) 不抛出
3,4) 任何 Compare 对象所抛的异常

复杂度

给定 map 的实例 c

1) 均摊常数
2) log(c.size()) + std::distance(first, last)
3) log(c.size()) + c.count(key)
4) log(c.size()) + c.count(x)

示例

#include <map>
#include <iostream>
int main()
{
    std::map<int, std::string> c = {
        {1, "one" }, {2, "two" }, {3, "three"},
        {4, "four"}, {5, "five"}, {6, "six"  }
    };
 
    // 从 c 擦除所有奇数
    for(auto it = c.begin(); it != c.end(); ) {
        if(it->first % 2 != 0)
            it = c.erase(it);
        else
            ++it;
    }
 
    for(auto& p : c) {
        std::cout << p.second << ' ';
    }
}

输出:

two four six

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

DR 应用于 出版时的行为 正确行为
LWG 2059 C++11 对一个 const_iterator 的重载引入了新的歧义 添加了对 iterator 的重载

参阅

清除内容
(公开成员函数)