命名空间
变体
操作

std::unordered_multiset<Key,Hash,KeyEqual,Allocator>::erase

来自 cppreference.cn
 
 
 
 
(1)
iterator erase( iterator pos );
(自 C++11 起)
(直到 C++23)
iterator erase( iterator pos )
    requires(!std::same_as<iterator, const_iterator>);
(自 C++23 起)
iterator erase( const_iterator pos );
(2) (自 C++11 起)
iterator erase( const_iterator first, const_iterator last );
(3) (自 C++11 起)
size_type erase( const Key& key );
(4) (自 C++11 起)
template< class K >
size_type erase( K&& x );
(5) (自 C++23 起)

从容器中移除指定的元素。剩余元素的顺序被保留。(这使得在迭代容器时可以移除单个元素。)

1,2) 移除位于 pos 的元素。如果 iteratorconst_iterator 是相同类型,则仅提供一个重载。
3) 移除范围 [firstlast) 中的元素,该范围必须是 *this 中的有效范围。
4) 移除所有键等价于 key 的元素。
5) 移除所有键与值 x 比较为等价的元素。仅当 Hash::is_transparentKeyEqual::is_transparent 有效且各自表示一种类型,并且 iteratorconst_iterator 都不能从 K 隐式转换时,此重载才参与重载解析。这假定此类 Hash 可以使用 KKey 类型调用,并且 KeyEqual 是透明的,这两者共同允许在不构造 Key 实例的情况下调用此函数。

指向已移除元素的引用和迭代器会失效。其他迭代器和引用不会失效。

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

内容

[编辑] 参数

pos - 要移除元素的迭代器
first, last - 定义要移除元素范围的迭代器对
key - 要移除元素的键值
x - 可以与表示要移除元素的键透明比较的任何类型的值

[编辑] 返回值

1-3) 紧随最后一个移除元素的迭代器。
4) 移除的元素数量。
5) 移除的元素数量。

[编辑] 异常

1-3) 不抛出任何异常。
4,5) HashKeyEqual 对象抛出的任何异常。

[编辑] 复杂度

给定 unordered_multiset 的实例 c

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

注意

特性测试 Std 特性
__cpp_lib_associative_heterogeneous_erasure 202110L (C++23) 关联容器无序关联容器中的异构擦除;重载 (5)

[编辑] 示例

#include <unordered_set>
#include <iostream>
 
int main()
{
    std::unordered_multiset<int> c = {1, 2, 3, 4, 1, 2, 3, 4};
 
    auto print = [&c]
    {
        std::cout << "c = { ";
        for (int n : c)
            std::cout << n << ' ';
        std::cout << "}\n";
    };
    print();
 
    std::cout << "Erase all odd numbers:\n";
    for (auto it = c.begin(); it != c.end();)
    {
        if (*it % 2 != 0)
            it = c.erase(it);
        else
            ++it;
    }
    print();
 
    std::cout << "Erase 1, erased count: " << c.erase(1) << '\n';
    std::cout << "Erase 2, erased count: " << c.erase(2) << '\n';
    std::cout << "Erase 2, erased count: " << c.erase(2) << '\n';
    print();
}

可能的输出

c = { 1 1 2 2 3 3 4 4 }
Erase all odd numbers:
c = { 2 2 4 4 }
Erase 1, erased count: 0
Erase 2, erased count: 2
Erase 2, erased count: 0
c = { 4 4 }

缺陷报告

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

DR 应用于 已发布行为 正确行为
LWG 2059 C++11 重载 (2) 存在歧义 添加了重载 (1)
LWG 2356 C++11 非等价元素的顺序,这些元素是
未擦除的元素不保证被保留
要求被保留

[编辑] 参见

清除内容
(公共成员函数) [编辑]