C++ STL unordered_map容器(深入了解,一文学会)

        iterator erase ( const_iterator position );unordered_map 无序map容器,正常map容器是有序的会自动执行排序功能,由于 unordered_map 容器底层采用的是哈希表存储结构,该结构本身不具有对数据的排序功能,所以此容器内部不会自行对存储的键值对进行排

  本文作者原创,转载请附上文章出处与本文链接。

C++ STL unordered_map容器(深入了解,一文学会)目录

1 unordered_map容器

1.1 unordered_map容器的成员函数

1.2 unordered_map容器创建

2 unordered_map迭代器

2.1 成员函数

2.2 使用方法

3 unordered_map获取元素

3.1下标访问

 3.2 at() 成员方法

 3.3 find() 成员方法

 3.4 begin()/end() 或者 cbegin()/cend()遍历

 4 unordered_map insert()

4.1 pair 类型的键值

4.2指定新键值对添加到容器中

 4.3 复制指定区域内的所有键值对

 4.4 添加多个键值对

 5 unordered_map emplace()和emplace_hint()方法

5.1 unordered_map emplace()方法

5.2 unordered_map emplace_hint()方法

6 unordered_map删除元素

6.1 unordered_map erase()方法

6.1.1 正向迭代器删除

6.1.2 根据Key删除

6.1.3 删除指定范围内的值

6.2 unordered_map clear()方法


1 unordered_map容器

        unordered_map 容器模板的定义

    template < class Key,                        //键值对中键的类型
               class T,                          //键值对中值的类型
               class Hash = hash<Key>,           //容器内部存储键值对所用的哈希函数
               class Pred = equal_to<Key>,       //判断各个键值对键相同的规则
               class Alloc = allocator< pair<const Key,T> >  // 指定分配器对象的类型
               > class unordered_map;
参数含义
<key,T>前 2 个参数分别用于确定键值对中键和值的类型,也就是存储键值对的类型。
Hash = hash<Key>用于指明容器在存储各个键值对时要使用的哈希函数,默认使用 STL 标准库提供的 hash<key> 哈希函数。注意,默认哈希函数只适用于基本数据类型(包括 string 类型),而不适用于自定义的结构体或者类。
Pred = equal_to<Key>要知道,unordered_map 容器中存储的各个键值对的键是不能相等的,而判断是否相等的规则,就由此参数指定。默认情况下,使用 STL 标准库中提供的 equal_to<key> 规则,该规则仅支持可直接用 == 运算符做比较的数据类型。

总的来说,当无序容器中存储键值对的键为自定义类型时,默认的哈希函数 hash 以及比较函数 equal_to 将不再适用,只能自己设计适用该类型的哈希函数和比较函数,并显式传递给 Hash 参数和 Pred 参数。

1.1 unordered_map容器的成员函数

成员方法功能
begin()返回指向容器中第一个键值对的正向迭代器。
end() 返回指向容器中最后一个键值对之后位置的正向迭代器。
cbegin()和 begin() 功能相同,只不过在其基础上增加了 const 属性,即该方法返回的迭代器不能用于修改容器内存储的键值对。
cend()和 end() 功能相同,只不过在其基础上,增加了 const 属性,即该方法返回的迭代器不能用于修改容器内存储的键值对。
empty()若容器为空,则返回 true;否则 false。
size()返回当前容器中存有键值对的个数。
max_size()返回容器所能容纳键值对的最大个数,不同的操作系统,其返回值亦不相同。
operator[key]该模板类中重载了 [] 运算符,其功能是可以向访问数组中元素那样,只要给定某个键值对的键 key,就可以获取该键对应的值。注意,如果当前容器中没有以 key 为键的键值对,则其会使用该键向当前容器中插入一个新键值对。
at(key)返回容器中存储的键 key 对应的值,如果 key 不存在,则会抛出 out_of_range 异常。 
find(key)查找以 key 为键的键值对,如果找到,则返回一个指向该键值对的正向迭代器;反之,则返回一个指向容器中最后一个键值对之后位置的迭代器(如果 end() 方法返回的迭代器)。
count(key)在容器中查找以 key 键的键值对的个数。
equal_range(key)返回一个 pair 对象,其包含 2 个迭代器,用于表明当前容器中键为 key 的键值对所在的范围。
emplace()向容器中添加新键值对,效率比 insert() 方法高。
emplace_hint()向容器中添加新键值对,效率比 insert() 方法高。
insert() 向容器中添加新键值对。
erase()删除指定键值对。
clear() 清空容器,即删除容器中存储的所有键值对。
swap()交换 2 个 unordered_map 容器存储的键值对,前提是必须保证这 2 个容器的类型完全相等。
bucket_count()返回当前容器底层存储键值对时,使用桶(一个线性链表代表一个桶)的数量。
max_bucket_count()返回当前系统中,unordered_map 容器底层最多可以使用多少桶。
bucket_size(n)返回第 n 个桶中存储键值对的数量。
bucket(key)返回以 key 为键的键值对所在桶的编号。
load_factor()返回 unordered_map 容器中当前的负载因子。负载因子,指的是的当前容器中存储键值对的数量(size())和使用桶数(bucket_count())的比值,即 load_factor() = size() / bucket_count()。
max_load_factor()返回或者设置当前 unordered_map 容器的负载因子。
rehash(n)将当前容器底层使用桶的数量设置为 n。
reserve()将存储桶的数量(也就是 bucket_count() 方法的返回值)设置为至少容纳count个元(不超过最大负载因子)所需的数量,并重新整理容器。
hash_function()返回当前容器使用的哈希函数对象。

1.2 unordered_map容器创建

	//创建NULL umap
	unordered_map<std::string, std::string> umap;

	//创建初始化过后的umap1
	unordered_map<std::string, std::string> umap1{
			{"C++", "csdn"},
			{"QT",  "csdn"},
			{"MFC", "csdn"} 
	};

	//创建umap2 的时候将 umap1 内容复制(拷贝)
	unordered_map<std::string, std::string> umap2(umap1);

        移动构造函数:

#include <unordered_map>
using namespace std;

//返回临时 unordered_map 容器的函数
unordered_map <std::string, std::string > retUmap() {
	std::unordered_map<std::string, std::string>tempUmap{
		{"C++", "csdn"},
		{"QT",  "csdn"},
		{"MFC", "csdn"}
	};
	return tempUmap;
}
int main()
{

	//调用移动构造函数,创建 umap2 容器
	unordered_map<std::string, std::string> umap2(retUmap());

}

        map有序容器&&unordered_map无序容器对比:

//创建NULL umap
unordered_map<std::string, std::string> umap1;

//创建初始化过后的umap1
unordered_map<std::string, std::string> umap{
		{"C++", "csdn"},
		{"QT",  "csdn"},
		{"MFC", "csdn"} 
};

//创建umap2 的时候将 umap1 内容复制(拷贝)
unordered_map<std::string, std::string> umap2(umap1);

for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}

cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;


//创建并初始化 map 容器
map<string, string>mymap{
		{"C++", "csdn"},
		{"QT",  "csdn"},
		{"MFC", "csdn"}
};
for (auto iter = mymap.begin(); iter != mymap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}

cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

2 unordered_map迭代器

        C++ STL 标准库中,unordered_map 容器迭代器的类型为前向迭代器(又称正向迭代器)。这意味着,假设 p 是一个前向迭代器,则其只能进行 *p、p++、++p 操作,且 2 个前向迭代器之间只能用 == 和 != 运算符做比较。

2.1 成员函数

成员方法功能
begin()返回指向容器中第一个键值对的正向迭代器。
end() 返回指向容器中最后一个键值对之后位置的正向迭代器。
cbegin()和 begin() 功能相同,只不过在其基础上增加了 const 属性,即该方法返回的迭代器不能用于修改容器内存储的键值对。
cend()和 end() 功能相同,只不过在其基础上,增加了 const 属性,即该方法返回的迭代器不能用于修改容器内存储的键值对。
find(key)查找以 key 为键的键值对,如果找到,则返回一个指向该键值对的正向迭代器;反之,则返回一个指向容器中最后一个键值对之后位置的迭代器(如果 end() 方法返回的迭代器)。
equal_range(key)返回一个 pair 对象,其包含 2 个迭代器,用于表明当前容器中键为 key 的键值对所在的范围。

值得一提的是,equal_range(key) 很少用于 unordered_map 容器,因为该容器中存储的都是键不相等的键值对,即便调用该成员方法,得到的 2 个迭代器所表示的范围中,最多只包含 1 个键值对。

2.2 使用方法

	//创建并初始化 map 容器
	unordered_map<string, string>umap{
			{"C++", "csdn1"},
			{"QT",  "csdn2"},
			{"MFC", "csdn3"}
	};

	cout << "umap 存储的键值对包括:" << endl;
	//遍历输出 umap 容器中所有的键值对
	for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
		cout << "<" << iter->first << ", " << iter->second << ">" << endl;
	}
	cout << "---------------------------------------------" << endl;
	cout << "---------------------------------------------" << endl;

	//获取指向指定键值对的前向迭代器
	unordered_map<string, string>::iterator iter = umap.find("QT");
	cout << "umap.find(\"QT\") = " << "<" << iter->first << ", " << iter->second << ">" << endl;
	cout << "---------------------------------------------" << endl;
	cout << "---------------------------------------------" << endl;

 操作 unordered_map 容器过程(尤其是向容器中添加新键值对)中,一旦当前容器的负载因子超过最大负载因子(默认值为 1.0),该容器就会适当增加桶的数量(通常是翻一倍),并自动执行 rehash() 成员方法,重新调整各个键值对的存储位置(此过程又称“重哈希”),此过程很可能导致之前创建的迭代器失效。重哈希只会影响遍历容器内键值对的顺序,整个遍历的操作仍然可以顺利完成。

3 unordered_map获取元素

        unordered_map获取元素的方法有4种

3.1下标访问

	//创建并初始化 map 容器
	unordered_map<string, string>umap{
			{"C++", "csdn1"},
			{"QT",  "csdn2"},
			{"MFC", "csdn3"}
	};

	string str = umap["QT"];
	cout << str << endl;
	cout << "---------------------------------------------" << endl;
	cout << "---------------------------------------------" << endl;

如果当前容器中并没有存储以 [ ] 运算符内指定的元素作为键的键值对,则此时 [ ] 运算符的功能将转变为:向当前容器中添加以目标元素为键的键值对。

 3.2 at() 成员方法

        unordered_map 类模板中,还提供有 at() 成员方法,和使用 [ ] 运算符一样,at() 成员方法也需要根据指定的键,才能从容器中找到该键对应的值;不同之处在于,如果在当前容器中查找失败,该方法不会向容器中添加新的键值对,而是直接抛出out_of_range异常。

//创建并初始化 map 容器
unordered_map<string, string>umap{
		{"C++", "csdn1"},
		{"QT",  "csdn2"},
		{"MFC", "csdn3"}
};

//获取指定键对应的值
string str = umap.at("QT");
cout << str << endl;

cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

//执行此语句会抛出 out_of_range 异常
try
{
	cout << umap.at("GO教程");
}
catch (const std::exception&)
{
	cout << "抛出 out_of_range 异常" << endl;
}

cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

 3.3 find() 成员方法

        [ ] 运算符和 at() 成员方法基本能满足大多数场景的需要。除此之外,还可以借助 unordered_map 模板中提供的 find() 成员方法。

        通过 find() 方法得到的是一个正向迭代器,该迭代器的指向分以下 2 种情况:

        当 find() 方法成功找到以指定元素作为键的键值对时,其返回的迭代器就指向该键值对;

        当 find() 方法查找失败时,其返回的迭代器和 end() 方法返回的迭代器一样,指向容器中最后一个键值对之后的位置。

//创建并初始化 map 容器
unordered_map<string, string>umap{
		{"C++", "csdn1"},
		{"QT",  "csdn2"},
		{"MFC", "csdn3"}
};

//查找成功
unordered_map<string, string>::iterator iter = umap.find("QT");
cout << iter->first << " " << iter->second << endl;

cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

//查找失败
unordered_map<string, string>::iterator iter2 = umap.find("Python");
if (iter2 == umap.end()) {
	cout << "当前容器中没有以\"Python\"为键的键值对";
}

cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

 3.4 begin()/end() 或者 cbegin()/cend()遍历

        除了 find() 成员方法之外,甚至可以借助 begin()/end() 或者 cbegin()/cend(),通过遍历整个容器中的键值对来找到目标键值对。

	//创建并初始化 map 容器
	unordered_map<string, string>umap{
			{"C++", "csdn1"},
			{"QT",  "csdn2"},
			{"MFC", "csdn3"}
	};
	//遍历整个容器中存储的键值对
	for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
		//判断当前的键值对是否就是要找的
		if (!iter->first.compare("QT")) {
			cout << iter->second << endl;
			break;
		}
	}
	cout << "---------------------------------------------" << endl;
	cout << "---------------------------------------------" << endl;

 4 unordered_map insert()

        unordered_map 模板类中,提供了多种语法格式的 insert() 方法,根据功能的不同,可划分为以下四种用法。

4.1 pair 类型的键值

        insert() 方法可以将 pair 类型的键值对元素添加到 unordered_map 容器中,其语法格式有 2 种:

//以普通方式传递参数
pair<iterator,bool> insert ( const value_type& val );
//以右值引用的方式传递参数
template <class P>
    pair<iterator,bool> insert ( P&& val );

以上 2 种格式中,参数 val 表示要添加到容器中的目标键值对元素;该方法的返回值为 pair类型值,内部包含一个 iterator 迭代器和 bool 变量:

  • 当 insert() 将 val 成功添加到容器中时,返回的迭代器指向新添加的键值对,bool 值为 True;
  • 当 insert() 添加键值对失败时,意味着当前容器中本就存储有和要添加键值对的键相等的键值对,这种情况下,返回的迭代器将指向这个导致插入操作失败的迭代器,bool 值为 False。
//创建空 umap 容器
unordered_map<string, string> umap;
//构建要添加的键值对
pair<string, string>mypair("C++", "csdn1");
//创建接收 insert() 方法返回值的pair类型变量
pair<unordered_map<string, string>::iterator, bool> ret;

//调用 insert() 方法的第一种语法格式
ret = umap.insert(mypair);
cout << "bool = " << ret.second << endl;
cout << "iter -> " << ret.first->first << " " << ret.first->second << endl;
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

//调用 insert() 方法的第二种语法格式
ret = umap.insert(make_pair("QT", "csdn2"));
cout << "bool = " << ret.second << endl;
cout << "iter -> " << ret.first->first << " " << ret.first->second << endl;
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

4.2指定新键值对添加到容器中

        insert() 方法还可以指定新键值对要添加到容器中的位置,其语法格式如下:

//以普通方式传递 val 参数
iterator insert ( const_iterator hint, const value_type& val );
//以右值引用方法传递 val 参数
template <class P>
    iterator insert ( const_iterator hint, P&& val );

以上 2 种语法格式中,hint 参数为迭代器,用于指定新键值对要添加到容器中的位置;val 参数指的是要添加容器中的键值对;方法的返回值为迭代器:

  • 如果 insert() 方法成功添加键值对,该迭代器指向新添加的键值对;
  • 如果 insert() 方法添加键值对失败,则表示容器中本就包含有相同键的键值对,该方法返回的迭代器就指向容器中键相同的键值对;

注意,以上 2 种语法格式中,虽然通过 hint 参数指定了新键值对添加到容器中的位置,但该键值对真正存储的位置,并不是 hint 参数说了算,最终的存储位置仍取决于该键值对的键的值。

//创建空 umap 容器
unordered_map<string, string> umap{
	{"a", "aa"},
	{"b", "bb"}
};
//构建要添加的键值对
pair<string, string>mypair("C++", "csdn1");
//创建接收 insert() 方法返回值的迭代器类型变量
unordered_map<string, string>::iterator iter;
//调用第一种语法格式
iter = umap.insert(umap.begin(), mypair);
cout << "iter -> " << iter->first << " " << iter->second << endl;
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

//调用第二种语法格式
iter = umap.insert(umap.begin(), make_pair("QT", "csdn2"));
cout << "iter -> " << iter->first << " " << iter->second << endl;
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

//遍历输出 umap 容器中所有的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << "<" << iter->first << ", " << iter->second << ">" << endl;
}
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

 4.3 复制指定区域内的所有键值对

        insert() 方法还支持将某一个 unordered_map 容器中指定区域内的所有键值对,复制到另一个 unordered_map 容器中,其语法格式如下:

template <class InputIterator>
    void insert ( InputIterator first, InputIterator last );

其中 first 和 last 都为迭代器,[first, last)表示复制其它 unordered_map 容器中键值对的区域。


//创建并初始化 umap 容器
unordered_map<string, string> umap{ 
	{"C++", "csdn1"},
	{"QT",  "csdn2"},
	{"MFC", "csdn3"}
};
//遍历 otherumap 容器中存储的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;


//创建一个空的 unordered_map 容器
unordered_map<string, string> otherumap;
//指定要拷贝 umap 容器中键值对的范围
unordered_map<string, string>::iterator first = ++umap.begin();
unordered_map<string, string>::iterator last = umap.end();
//将指定 umap 容器中 [first,last) 区域内的键值对复制给 otherumap 容器
otherumap.insert(first, last);

//遍历 otherumap 容器中存储的键值对
for (auto iter = otherumap.begin(); iter != otherumap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

 4.4 添加多个键值对

        除了以上 3 种方式,insert() 方法还支持一次向 unordered_map 容器添加多个键值对,其语法格式如下:

void insert ( initializer_list<value_type> il );

其中,il 参数指的是可以用初始化列表的形式指定多个键值对元素。

//创建空的 umap 容器
unordered_map<string, string> umap;
//向 umap 容器同时添加多个键值对
umap.insert(
	{ 
		{"C++", "csdn1"},
		{"QT",  "csdn2"},
		{"MFC", "csdn3"}
	}
);
//遍历输出 umap 容器中存储的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}

cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

 5 unordered_map emplace()和emplace_hint()方法

        和 map、set 等容器一样,C++ 11 标准也为 unordered_map 容器新增了 emplace() 和 emplace_hint() 成员方法。

        实现向已有 unordered_map 容器中添加新键值对,可以通过调用 insert() 方法,但其实还有更好的方法,即使用 emplace() 或者 emplace_hint() 方法,它们完成“向容器中添加新键值对”的效率,要比 insert() 方法高。

5.1 unordered_map emplace()方法

        emplace() 方法的用法很简单,其语法格式如下:

template <class... Args>
    pair<iterator, bool> emplace ( Args&&... args );

其中,参数 args 表示可直接向该方法传递创建新键值对所需要的 2 个元素的值,其中第一个元素将作为键值对的键,另一个作为键值对的值。也就是说,该方法无需我们手动创建键值对,其内部会自行完成此工作。

另外需要注意的是,该方法的返回值为 pair 类型值,其包含一个迭代器和一个 bool 类型值:

  • 当 emplace() 成功添加新键值对时,返回的迭代器指向新添加的键值对,bool 值为 True;
  • 当 emplace() 添加新键值对失败时,说明容器中本就包含一个键相等的键值对,此时返回的迭代器指向的就是容器中键相同的这个键值对,bool 值为 False。
//创建 umap 容器
unordered_map<string, string> umap;
//定义一个接受 emplace() 方法的 pair 类型变量
pair<unordered_map<string, string>::iterator, bool> ret;
//调用 emplace() 方法
ret = umap.emplace("C++", "csdn1");
//输出 ret 中包含的 2 个元素的值
cout << "bool =" << ret.second << endl;
cout << "iter ->" << ret.first->first << " " << ret.first->second << endl;
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

ret = umap.emplace("QT", "csdn2");
cout << "bool =" << ret.second << endl;
cout << "iter ->" << ret.first->first << " " << ret.first->second << endl;
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

 通过执行结果中 bool 变量的值为 1 可以得知,emplace() 方法成功将新键值对添加到了 umap 容器中。

5.2 unordered_map emplace_hint()方法

       emplace_hint() 方法的语法格式如下:

template <class... Args>
    iterator emplace_hint ( const_iterator position, Args&&... args );

和 emplace() 方法相同,emplace_hint() 方法内部会自行构造新键值对,因此我们只需向其传递构建该键值对所需的 2 个元素(第一个作为键,另一个作为值)即可。不同之处在于:

  • emplace_hint() 方法的返回值仅是一个迭代器,而不再是 pair 类型变量。当该方法将新键值对成功添加到容器中时,返回的迭代器指向新添加的键值对;反之,如果添加失败,该迭代器指向的是容器中和要添加键值对键相同的那个键值对。
  • emplace_hint() 方法还需要传递一个迭代器作为第一个参数,该迭代器表明将新键值对添加到容器中的位置。需要注意的是,新键值对添加到容器中的位置,并不是此迭代器说了算,最终仍取决于该键值对的键的值。

可以这样理解,emplace_hint() 方法中传入的迭代器,仅是给 unordered_map 容器提供一个建议,并不一定会被容器采纳。

	//创建 umap 容器
	unordered_map<string, string> umap;
	//定义一个接受 emplace_hint() 方法的迭代器
	unordered_map<string, string>::iterator iter;
	//调用 empalce_hint() 方法
	iter = umap.emplace_hint(umap.begin(), "C++", "csdn1");
	//输出 emplace_hint() 返回迭代器 iter 指向的键值对的内容
	cout << "iter ->" << iter->first << " " << iter->second << endl;
	cout << "---------------------------------------------" << endl;
	cout << "---------------------------------------------" << endl;

	iter = umap.emplace_hint(umap.begin(), "C++", "csdn1");
	//输出 emplace_hint() 返回迭代器 iter 指向的键值对的内容
	cout << "iter ->" << iter->first << " " << iter->second << endl;
	cout << "---------------------------------------------" << endl;
	cout << "---------------------------------------------" << endl;

	for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
		cout << iter->first << " " << iter->second << endl;
	}
	cout << "---------------------------------------------" << endl;
	cout << "---------------------------------------------" << endl;

6 unordered_map删除元素

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

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

6.1 unordered_map erase()方法

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

6.1.1 正向迭代器删除

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

iterator erase ( const_iterator position );

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

//创建 umap 容器
unordered_map<string, string> umap
{
	{"C++", "csdn1"},
	{"QT",  "csdn2"},
	{"MFC", "csdn3"}
};
//输出 umap 容器中存储的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}
cout << "erase:" << endl;
//定义一个接收 erase() 方法的迭代器
unordered_map<string, string>::iterator ret;
//删除容器中第一个键值对
ret = umap.erase(umap.begin());
//输出 umap 容器中存储的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}
cout << "ret = " << ret->first << " " << ret->second << endl;

 可以看到,通过给 erase() 方法传入指向容器中第一个键值对的迭代器,该方法可以将容器中第一个键值对删除,同时返回一个指向被删除键值对之后位置的迭代器。

注意,如果erase()方法删除的是容器存储的最后一个键值对,则该方法返回的迭代器,将指向容器中最后一个键值对之后的位置(等同于 end() 方法返回的迭代器)。

6.1.2 根据Key删除

        我们还可以直接将要删除键值对的键作为参数直接传给 erase() 方法,该方法会自行去 unordered_map 容器中找和给定键相同的键值对,将其删除。erase() 方法的语法格式如下:

size_type erase ( const key_type& k );

//创建 umap 容器
unordered_map<string, string> umap
{
	{"C++", "csdn1"},
	{"QT",  "csdn2"},
	{"MFC", "csdn3"}
};
//输出 umap 容器中存储的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}
int delNum = umap.erase("MFC");
cout << "delNum = " << delNum << endl;
//再次输出 umap 容器中存储的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}

6.1.3 删除指定范围内的值

        除了支持删除 unordered_map 容器中指定的某个键值对,erase() 方法还支持一次删除指定范围内的所有键值对,其语法格式如下:

iterator erase ( const_iterator first, const_iterator last );

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

//创建 umap 容器
unordered_map<string, string> umap{
	{"C++", "csdn1"},
	{"QT",  "csdn2"},
	{"MFC", "csdn3"} 
};
//输出 umap 容器中存储的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

//first 指向第一个键值对
unordered_map<string, string>::iterator first = ++umap.begin();
//last 指向最后一个键值对
unordered_map<string, string>::iterator last = umap.end();
//删除[fist,last)范围内的键值对
auto ret = umap.erase(first, last);
//输出 umap 容器中存储的键值对
for (auto iter = umap.begin(); iter != umap.end(); ++iter) {
	cout << iter->first << " " << iter->second << endl;
}
cout << "---------------------------------------------" << endl;
cout << "---------------------------------------------" << endl;

6.2 unordered_map clear()方法

        clear()容器通用清楚数据方法。

void clear()

以下博客部分内容借鉴自:http://c.biancheng.net/stl/。

C++ STL 容器、迭代器、适配器(深入了解,一文学会)    https://blog.csdn.net/qq_37529913/article/details/120052137                                                                                C++ STL deque容器(深入了解,一文学会)                       https://blog.csdn.net/qq_37529913/article/details/118676574
C++ STL vector容器(深入了解,一文学会)                       https://blog.csdn.net/qq_37529913/article/details/118676109
C++ STL list容器(深入了解,一文学会)                             https://blog.csdn.net/qq_37529913/article/details/118676917
C++ STL forward_list容器(深入了解,一文学会)               https://blog.csdn.net/qq_37529913/article/details/118687348
C++ STL array 容器(深入了解,一文学会)                        https://blog.csdn.net/qq_37529913/article/details/118688364
C++ STL pair 类模板(深入了解,一文学会)                       https://blog.csdn.net/qq_37529913/article/details/118714852
C++ STL map容器(深入了解,一文学会)                           https://blog.csdn.net/qq_37529913/article/details/118741670
C++ STL map emplace()和emplace_hint()(深入了解,一文学会)         https://blog.csdn.net/qq_37529913/article/details/118771777
C++ STL multimap容器(深入了解,一文学会)                    https://blog.csdn.net/qq_37529913/article/details/118773021
C++ STL Set容器(深入了解,一文学会)                             https://blog.csdn.net/qq_37529913/article/details/118918940
C++ STL multiset容器(深入了解,一文学会)                      https://blog.csdn.net/qq_37529913/article/details/119624779
C++ STL unordered_map容器(深入了解,一文学会)         https://blog.csdn.net/qq_37529913/article/details/119689199
C++ STL unordered_set容器(深入了解,一文学会)           https://blog.csdn.net/qq_37529913/article/details/119709019
C++ STL unordered_multiset容器(深入了解,一文学会)    https://blog.csdn.net/qq_37529913/article/details/119709079
C++ STL stack容器适配器(深入了解,一文学会)        https://blog.csdn.net/qq_37529913/article/details/119723782
C++ STL queue容器适配器(深入了解,一文学会)       https://blog.csdn.net/qq_37529913/article/details/119746246
C++ STL priority_queue容器适配器(深入了解,一文学会)                https://blog.csdn.net/qq_37529913/article/details/119770527
C++ STL reverse_iterator反向迭代器适配器(深入了解,一文学会)   https://blog.csdn.net/qq_37529913/article/details/119814820
C++ STL insert_iterator插入迭代器适配器(深入了解,一文学会)      https://blog.csdn.net/qq_37529913/article/details/119834378
C++ STL stream_iterator流迭代器(深入了解,一文学会)                  https://blog.csdn.net/qq_37529913/article/details/119834429
C++ STL streambuf_iterator流缓冲区迭代器(深入了解,一文学会)        https://blog.csdn.net/qq_37529913/article/details/119850048
C++ STL move_iterator移动迭代器(深入了解,一文学会)                      https://blog.csdn.net/qq_37529913/article/details/119859888
C++ STL advance()函数(深入了解,一文学会)        https://blog.csdn.net/qq_37529913/article/details/120008250
C++ STL distance()函数(深入了解,一文学会)        https://blog.csdn.net/qq_37529913/article/details/120008300
C++ STL iterator迭代器(深入了解,一文学会)         https://blog.csdn.net/qq_37529913/article/details/120008346
C++ STL const_iterator转换为iterator类型迭代器(深入了解,一文学会)        https://blog.csdn.net/qq_37529913/article/details/120008324
C++ STL begin()和end()函数(深入了解,一文学会)        https://blog.csdn.net/qq_37529913/article/details/120008459
C++ STL prev()和next()函数(深入了解,一文学会)         https://blog.csdn.net/qq_37529913/article/details/120008481
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

双子座断点

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值