C++ STL unordered_map删除元素:erase()和clear()

1年前 (2024-04-27)

C++ STL 标准库为了方便用户可以随时删除 unordered_map 容器中存储的键值对,unordered_map 容器类模板中提供了以下 2 个成员方法:

  • erase():删除 unordered_map 容器中指定的键值对;

  • clear():删除 unordered_map 容器中所有的键值对,即清空容器。


本节就对以上 2 个成员方法的用法做详细的讲解。

unordered_map erase()方法

为了满足不同场景删除 unordered_map 容器中键值对的需要,此容器的类模板中提供了 3 种语法格式的 erase() 方法。

1) erase() 方法可以接受一个正向迭代器,并删除该迭代器指向的键值对。该方法的语法格式如下:

iterator erase ( const_iterator position );

其中 position 为指向容器中某个键值对的迭代器,该方返回一个指向被删除键值对之后位置的迭代器。

举个例子:

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建 umap 容器

unordered_map<string, string> umap{

{"STL教程", "http://c.biancheng网站站点" rel="nofollow" /> STL教程 http://c.biancheng网站站点" rel="nofollow" />

size_type erase ( const key_type& k );

其中,k 表示目标键值对的键的值;该方返回一个整数,其表示成功删除的键值对的数量。

举个例子:

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建 umap 容器

unordered_map<string, string> umap{

{"STL教程", "http://c.biancheng网站站点" rel="nofollow" /> STL教程 http://c.biancheng网站站点" rel="nofollow" />

iterator erase ( const_iterator first, const_iterator last );

其中 first 和 last 都是正向迭代器,[first, last) 范围内的所有键值对都会被 erase() 方法删除;同时,该方返回一个指向被删除的一个键值对之后一个位置的迭代器。

举个例子:

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建 umap 容器

unordered_map<string, string> umap{

{"STL教程", "http://c.biancheng网站站点" rel="nofollow" />

void clear()


举个例子:

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建 umap 容器

unordered_map<string, string> umap{

{"STL教程", "http://c.biancheng网站站点" rel="nofollow" /> STL教程 http://c.biancheng网站站点" rel="nofollow" />