如果我们需要向 STL 中的 map 容器插入元素有三种方法,即,使用下标索引的形式和使用 insert 方法插入元素还可以使用 emplace 方法。
map[key] = value
参数 | 说明 |
---|---|
map | 需要插入值的 map。 |
key | 需要插入的键。 |
value | 需要插入的值。 |
如果键 key 不存在,则插入键和对应的值,否则,会将键 key 的值更新为 value。
//引用传递一个键值对
pair<iterator,bool> insert (const value_type& val);
//以右值引用的方式传递键值对
template <class P>
pair<iterator,bool> insert (P&& val);
//以普通引用的方式传递 val 参数
iterator insert (const_iterator position, const value_type& val);
//以右值引用的方式传递 val 键值对参数
template <class P>
iterator insert (const_iterator position, P&& val);
参数 | 说明 |
---|---|
position | 需要插入的位置。 |
val | 需要插入的键。 |
在位置 position 插入值 val。
insert 方法会返回一个 pair 对象,其中 pair.first 表示一个迭代器,pair.second 为一个 bool 类型变量,如果成功插入 val,则该迭代器指向新插入的 val,bool 值为 true。
如果插入 val 失败,则表明当前 map 容器中存有和 val 的键相同的键值对(用 p 表示),此时返回的迭代器指向 p,bool 值为 false。
使用下标索引给 map 插入元素
#include <iostream>
#include <map>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
map<string, string> map1{{"name", "haicoder"}, {"url", "haicoder.net"}};
map1["online"] = "yes";
for (auto iter = map1.begin(); iter != map1.end(); ++iter)
{
cout << iter->first << " " << iter->second << endl;
}
return 0;
}
因为,这里需要使用 C++ 11,因此,我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ map.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们看到,我们使用了下标索引的方式将元素插入到了 map 中。
使用 insert 给 map 插入元素
#include <iostream>
#include <map>
using namespace std;
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
//创建一个空 map 容器
std::map<string, string> mymap;
//创建一个真实存在的键值对变量
std::pair<string, string> CPP = { "C++教程", "https://haicoder.net/cpp/cpp-tutorial.html" };
//创建一个接收 insert() 方法返回值的 pair 对象
std::pair<std::map<string, string>::iterator, bool> ret;
//插入CPP,由于CPP并不是临时变量,因此会以第一种方式传参
ret = mymap.insert(CPP);
cout << "ret.iter = <{" << ret.first->first << ", " << ret.first->second << "}, " << ret.second << ">" << endl;
//以右值引用的方式传递临时的键值对变量
ret = mymap.insert({ "golang","https://haicoder.net/golang/golang-tutorial.html" });
cout << "ret.iter = <{" << ret.first->first << ", " << ret.first->second << "}, " << ret.second << ">" << endl;
//插入失败样例
ret = mymap.insert({ "C++教程","https://haicoder.net/cpp/cpp-tutorial.html" });
cout << "ret.iter = <{" << ret.first->first << ", " << ret.first->second << "}, " << ret.second << ">" << endl;
return 0;
}
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们看到,我们使用了 insert 将元素插入到了 map 中。
如果我们需要向 STL 中的 map 容器插入元素有三种方法,即,使用下标索引的形式和使用 insert 方法插入元素。