C++|STL學習筆記-對STL中關聯容器map的進一步認識
阿新 • • 發佈:2018-11-16
關聯容器map
key + value 的值
關聯容器 = 有序容器(紅黑樹) + 無序容器(散列表) + hash_map
有序容器中:
map的鍵值是不允許重複的
multimap的鍵值是允許重複的
set是一個集合,鍵值=實值,就是隻包含一個值,既是鍵值也是實值,不允許重複
multiset執行重複
map
底層就是紅黑樹(平衡排序二叉樹)
鍵值儲存,高效訪問
插入效率低於連結串列,因為涉及排序
下面是一段插入程式碼,菜雞一般是這麼寫的:
#include <map> #include <iostream> using namespace std; void MapConstruct(){ map<int, char> mp; mp.insert(pair<int, char>(1, 'a')); return; } int main(){ MapConstruct(); getchar(); return 0; }
區域性變數結構如下:
‘
進價一點點的寫法如下程式碼(稍微有工作經驗的人一般是這麼寫的)
#include <map> #include <iostream> using namespace std; void MapConstruct(){ typedef pair<int, char> in_pair; map<int, char> mp; mp.insert(in_pair(1, 'a')); //mp.insert(pair<int, char>(1, 'a')); return; } int main(){ MapConstruct(); getchar(); return 0; }
區域性變數結構如下:
遍歷一下:
#include <map> #include <iostream> #include <algorithm> using namespace std; typedef pair<int, char> in_pair; void fun(in_pair pr){ cout << pr.first << "\t" << pr.second << endl; } void MapConstruct(){ map<int, char> mp; mp.insert(in_pair(1, 'a')); mp.insert(in_pair(2, 'b')); mp.insert(in_pair(3, 'c')); mp.insert(in_pair(4, 'd')); for_each(mp.begin(), mp.end(), fun); return; } int main(){ MapConstruct(); getchar(); return 0; }
執行截圖如下:
然後,大佬的寫法(標準寫法,一般是這種寫法)
不得不說,大佬和小菜的最大區別就是大佬想得比較周到:
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, char> in_pair;
typedef pair<map<int, char>::iterator, bool> in_pair_bool;
void judgeOk(in_pair_bool pr){
if(pr.second){
cout << "插入成功!" << endl;
}
else{
cout << "插入失敗!" << endl;
}
}
void fun(in_pair pr){
cout << pr.first << "\t" << pr.second << endl;
}
void MapConstruct(){
map<int, char> mp;
pair<map<int, char>::iterator, bool> pr;
pr = mp.insert(in_pair(1, 'a'));
judgeOk(pr);
pr = mp.insert(in_pair(2, 'b'));
judgeOk(pr);
pr = mp.insert(in_pair(3, 'c'));
judgeOk(pr);
pr = mp.insert(in_pair(4, 'd'));
judgeOk(pr);
pr = mp.insert(in_pair(1, 'e'));
judgeOk(pr);
for_each(mp.begin(), mp.end(), fun);
return;
}
int main(){
MapConstruct();
getchar();
return 0;
}
執行截圖如下: