c/c++ 標準庫 map set 插入
阿新 • • 發佈:2018-09-23
返回 小例子 rst test true git str head size
標準庫 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; }
github完整代碼
c/c++ 學習互助QQ群:877684253
本人微信:xiaoshitou5854
c/c++ 標準庫 map set 插入