C++ unordered_map insert()用法精讲
unordered_map 模板类中,提供了多种语法格式的 insert() 方法,根据功能的不同,可划分为以下几种用法。
1) insert() 方法可以将 pair 类型的键值对元素添加到 unordered_map 容器中,其语法格式有 2 种:
//以普通方式传递参数
pair<iterator,bool> insert ( const value_type& val );
//以右值引用的方式传递参数
template <class P>
pair<iterator,bool> insert ( P&& val );
有关右值引用,可阅读《C++右值引用详解》一文,这里不再做具体解释。
以上 2 种格式中,参数 val 表示要添加到容器中的目标键值对元素;该方法的返回值为 pair类型值,内部包含一个 iterator 迭代器和 bool 变量:
当 insert() 将 val 成功添加到容器中时,返回的迭代器指向新添加的键值对,bool 值为 True;
当 insert() 添加键值对失败时,意味着当前容器中本就存储有和要添加键值对的键相等的键值对,这种情况下,返回的迭代器将指向这个导致插入操作失败的迭代器,bool 值为 False。
举个例子:
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
//创建空 umap 容器
unordered_map<string, string> umap;
//构建要添加的键值对
std::pair<string, string>mypair("STL教程", "http://c.biancheng网站站点" rel="nofollow" />
bool = 1
iter -> STL教程 http://c.biancheng网站站点" rel="nofollow" />//以普通方式传递 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 参数说了算,最终的存储位置仍取决于该键值对的键的值。
举个例子:
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
//创建空 umap 容器
unordered_map<string, string> umap;
//构建要添加的键值对
std::pair<string, string>mypair("STL教程", "http://c.biancheng网站站点" rel="nofollow" />
其中 first 和 last 都为迭代器,iter -> STL教程 http://c.biancheng网站站点" rel="nofollow" /> template <class InputIterator> void insert ( InputIterator first, InputIterator last );
[first, last)
表示其它 unordered_map 容器中键值对的区域。
举个例子:#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
//创建并初始化 umap 容器
unordered_map<string, string> umap{ {"STL教程","http://c.biancheng网站站点" rel="nofollow" />
其中,il 参数指的是可以用初始化列表的形式指定多个键值对元素。Python教程 http://c.biancheng网站站点" rel="nofollow" /> void insert ( initializer_list<value_type> il );
举个例子:
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
//创建空的 umap 容器
unordered_map<string, string> umap;
//向 umap 容器同时添加多个键值对
umap.insert({ {"STL教程","http://c.biancheng网站站点" rel="nofollow" />
STL教程 http://c.biancheng网站站点" rel="nofollow" />