STL中的map和unordered_map
map
頭文件 #include <map>
原理:std::map的內部實現了一顆紅黑樹,有對其鍵值進行排序的功能,所以map是一個有序的容器,map中的每一個元素都是紅黑樹的一個節點,插入、刪除、查找等操作的復雜度都是logn的
//定義
map<int,int> mp
//插入
1.mp.insert(pair<int, int>(x, y));
2.mp[x]+=y;
//刪除
mp.erase(x);
mp.erase(mp.begin(),mp.end());//刪除區間是一個前閉后開的區間
//迭代
map<int,int>::iterator it;
for(it=mp.begin();it!=mp.end();it++)
//利用迭代器查找鍵值或者直接得到該節點的值
mp[x];
map<int, int>::iterator it;//得到的迭代器是一個pair對象,鍵是 //first,值是second
it = mp.find(x);
cout << it->second << endl;
cout << (*it).second << endl;
//大小
mp.size();
unordered_map
頭文件 #include <unordered_map>
原理:std::unordered_map的內部實現了一個哈希表,其中的元素的無序的,unordered_map中每個特定的key都會通過一些特定的哈希運算到一個特定的位置,這個特定的位置可能重復,所以這個位置有多個元素,將這個位置稱為哈希桶
用法和map 是差不多的就不詳細介紹了
區別
map查找比unordered_map慢一些
unordered_map的建立會比map慢很多
這樣,如果我們建樹后就不需要多次查詢的話就用unordered_map
建樹后需要修改的話就用map吧
還是看實際情況選擇
