C++關聯容器之unordered-map
阿新 • • 發佈:2021-06-30
-
主要著眼於unordered_map的基本操作,會用即可。
-
unordered_map是C++中的雜湊表,可以在任意型別和任意型別間做對映。
-
基本操作如下:
-
使用需要
#include<unordered_map>
-
定義一個hashtable,
unordered_map<int,int>,
unordered_map<string,double>
...... -
插入:例如將
("ABC" -> 5.45)
插入unordered_map<string, double> hash
中,hash["ABC"]=5.45
-
查詢:
hash["ABC"]
-
判斷key是否存在:
hash.count("ABC") != 0
或hash.find("ABC") != hash.end()
-
遍歷
for(auto &c : hash)cout<<c.first<<" "<<c.second<<endl; //法1 for(auto &[k,v] : hash)cout<<k<<" "<<v<<endl; //法2
-
如果想讓自定義的class作為key(
unordered_map<key,value>
-
雜湊函式,需要實現一個class過載
operator()
,將自定義class變數對映到一個size_t
型別的數。一般常用std::hash
模板來實現。 -
判斷兩個自定義class型別的變數是否相等的函式,一般在自定義class裡過載
operator==
。 -
示例程式碼
#include <iostream> #include <vector> #include <unordered_map> using namespace std; class Myclass { public: int first; vector<int> second; // 過載等號,判斷兩個Myclass型別的變數是否相等 bool operator== (const Myclass &other) const { return first == other.first && second == other.second; } }; // 實現Myclass類的hash函式 namespace std { template <> struct hash<Myclass> { size_t operator()(const Myclass &k) const { int h = k.first; for (auto x : k.second) { h ^= x; } return h; } }; } int main() { unordered_map<Myclass, double> S; Myclass a = { 2, {3, 4} }; Myclass b = { 3, {1, 2, 3, 4} }; S[a] = 2.5; S[b] = 3.123; cout << S[a] << ' ' << S[b] << endl; return 0; }
-
-