标准库 map set 插入
一, 插入操作
有 map 如下:
map<string, size_t> cnt;
插入方法:
插入操作种类 | 功能描述 |
---|---|
cnt.insert({"abc", 12}); | 直接用大括号 |
cnt.insert(make_pari("abc", 22)); | 用 make_pair 函数,返回一个 pair |
cnt.insert(pair<string, size_t>("abc", 22)); | 直接构造 pair |
cnt.insert(map<string, size_t>::value_type("abc",31)); | 有 map 的 value_type |
插入注意: map,set 没有重复的 key, 所以插入重复 key 的 pair 时, 实际是没有插入进去的.
- map<int, int> mp{
- {
- 1,2
- },{
- 2,3
- }
- };
- mp.insert({
- 1,3
- });//{
- 1,3
- }的 key 和 {
- 1,2
- } 重复了, 所以 mp 还是原来的:{
- 1,2
- },{
- 2,3
- }
二, map 和 multimap 的插入单一值的返回值
类型 | 功能描述 |
---|---|
map | 返回一个 pair.first 是迭代器,second 是 bool,插入成功 second 为 true |
multimap | 返回一个迭代器 |
小例子索引
代码块 | 功能描述 |
---|---|
test1 | 4 种插入方式 |
test2 | map insert 的返回值 |
test3 | multimap insert 的返回值 |
小例子:
- #include <iostream>
- #include <set>
- #include <map>
- #include <vector>
- using namespace std;
- int main(){
- //test1 4 种插入方式
- /*
- map<int, int> mp{{1,2},{2,3}};
- // 方式 1
- mp.insert({1,3});//insert 不成功, 因为 key1 已经存在
- // 方式 2
- mp.insert(make_pair(3,4));
- // 方式 3
- mp.insert(pair<int,int>(4,1));
- // 方式 4
- mp.insert(map<int,int>::value_type(5,1));
- for(auto &s : mp){
- cout <<s.first << "," << s.second << endl;
- }
- */
- //test2 map insert 的返回值
- /*
- map<string, size_t> cnt;
- string wd;
- while(cin>> wd){
- //map 和 setinsert 的返回值类型如下, 用 auto 也可以
- pair<map<string, size_t>::iterator, bool> ret =
- cnt.insert({wd, 1});
- //auto ret = cnt.insert({wd, 1});
- if(!ret.second){
- ++ret.first->second;
- }
- }
- for(auto &s : cnt){
- cout <<s.first << ":" << s.second << endl;
- }
- */
- //test3 multimap insert 的返回值
- multimap<string, size_t> aus;
- aus.insert({"aaa", 1});
- //multi 的返回值类型如下
- map<string, size_t>::iterator ret = aus.insert({"aaa", 2});
- cout <<ret->first <<":" << ret->second << endl;
- }
来源: http://www.bubuko.com/infodetail-2778073.html