unordered_mapとmapのC ++ STL共通操作
前書き:
mapとunordered_mapに格納されている内容は同じで、どちらも(key、value)です。
違い:
1.マップには赤黒木が組み込まれており、unordered_mapにはハッシュテーブルが組み込まれています。
2.マップには並べ替え機能があり、unordered_mapの要素は順序付けられていません。
3.マップクエリ、挿入、および削除操作の時間計算量はO(logn)であり、unordered_mapの検索時間計算量はO(1)です。
4.マップには赤黒木が組み込まれているため、各ノードは親ノードとその他のコンテンツを追加で保存する必要があるため、メモリフットプリントは大きくなりますが、unordered_mapはさらに大きくなります。
注:ハッシュテーブルのクエリ時間はO(1)ですが、unordered_mapのクエリ時間は必ずしもmapのクエリ時間よりも短いとは限りません。データ量を考慮すると、unordered_mapのハッシュ関数の構築速度は比較的遅いため、特定の状況、特定の分析、特定の選択!
#include<unordered_map>
一般的な操作:
#include<iostream>
#include<unordered_map>
#include<string>
using namespace std;
int main() {
unordered_map<int,string> um;
um.insert(pair<int,string>(1,"one")); //一般插入
um[3] = "three"; //数组的形式,如果存在就修改,否则插入
um.insert(pair<int,string>(2,"two"));
um[2] = "twotwo"; //修改
for(auto it = um.begin();it != um.end();++it) //begin,end,迭代器
cout<<it->first<<" "<<it->second<<"\n";
cout<<"um'size = "<<um.size()<<"\n"; //size
if(um.empty()) //empty
cout<<"um is empty!"<<"\n";
else
cout<<"um is not empty"<<"\n";
auto it = um.find(1); //find
if(it != um.end())
cout<<it->first<<" "<<it->second<<"\n";
cout<<um.count(2)<<"\n"; //count
return 0;
}
出力:
2 twotwo
1 one
3 three
um'size = 3
um is not empty
1 one
1