std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::erase

来自cppreference.com

 
 
容器库
序列
(C++11)
关联
无序关联
适配器
视图
(C++20)
 
 
(1)
iterator erase( iterator pos );
(C++11 起)
iterator erase( const_iterator pos );
(C++11 起)
(2)
iterator erase( const_iterator first, const_iterator last );
(C++11 起)
size_type erase( const key_type& key );
(3) (C++11 起)
template< class K >
size_type erase( K&& x );
(4) (C++23 起)

从容器移除指定的元素。

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

到被擦除元素的引用和迭代器被非法化。其他迭代器和引用不被非法化。

迭代器 pos 必须合法且可解引用。从而 end() 迭代器(合法,但不可解引用)不能用作 pos 所用的值。 保留未被擦除的元素顺序(这使得可能在迭代通过容器时擦除单独的元素)。

参数

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

返回值

1-2) 后随最后被移除的元素的迭代器。
3,4) 被移除的元素数。

异常

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

复杂度

给定 unordered_map 的实例 c

1) 平均情况:常数,最坏情况: c.size()
2) 平均情况: std::distance(first, last) ,最坏情况: c.size()
3) 平均情况: c.count(key) ,最坏情况: c.size()
4) 平均情况: c.count(x) ,最坏情况: c.size()

示例

#include <unordered_map>
#include <iostream>
int main()
{
    std::unordered_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 的重载
LWG 2356 C++11 未被擦除的元素顺序未指定 要求保留

参阅

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