C++ map與unordered_map
阿新 • • 發佈:2021-01-12
1.區別
map:本質紅黑樹,插入新資料後自動排序,存放的資料是有序的
unordered_map:本質雜湊表,資料無序,根據插入資料的順序排列,查詢速度快。
使用上,map與unordered_map的函式都一樣,如果不需要排序,使用unordered_map即可。
2.標頭檔案
map:#include<map>
unordered_map:#include<unordered_map>
3.使用
1.定義 map<int,char> p; 2.新增元素 p[3]='a'; p[2]='c'; 3.刪除 p.erase(2); 4.查詢 if(p.count(3)==1) cout<<"存在"; if(p.count(5)==0) cout<<"不存在"; 5.大小 cout<<p.size();
unordered_map與map類似。
4.舉例
#include <iostream> #include <map> using namespace std; int main() { map<int, char> p; p[0] = 'a'; p[3] = 'c'; p[1] = 'b'; map<int, char>::iterator it; it = p.begin(); cout << "map中的元素為:" << endl; while (it != p.end()) { cout << it->first << " " << it->second << endl; it++; } p.erase(0);//刪除元素 cout << endl << "刪除後的元素為:" << endl; it = p.begin(); while (it != p.end()) { cout << it->first << " " << it->second << endl; it++; } cout << endl << "大小為:" << p.size() << endl; if (p.count(4) == 0) cout << "4不存在map中" << endl; if (p.count(3) == 0) cout << "3存在map中" << endl; return 0; }
使用map,打印出的資料是有序的,即按照0,1,3的順序列印,如果替換成unordered_map,則按照插入的順序進行列印,即0,3,1。