1. 程式人生 > 其它 >C++關聯容器之unordered-map

C++關聯容器之unordered-map

  • 主要著眼於unordered_map的基本操作,會用即可。

  • unordered_map是C++中的雜湊表,可以在任意型別和任意型別間做對映。

  • 基本操作如下:

    1. 使用需要#include<unordered_map>

    2. 定義一個hashtable,unordered_map<int,int>, unordered_map<string,double>......

    3. 插入:例如將("ABC" -> 5.45) 插入unordered_map<string, double> hash中,hash["ABC"]=5.45

    4. 查詢:hash["ABC"]

      會返回5.45

    5. 判斷key是否存在:hash.count("ABC") != 0hash.find("ABC") != hash.end()

    6. 遍歷

      for(auto &c : hash)cout<<c.first<<" "<<c.second<<endl;                        //法1
      for(auto &[k,v] : hash)cout<<k<<" "<<v<<endl;                                 //法2
      
    7. 如果想讓自定義的class作為key(unordered_map<key,value>

      )來使用unordered_map,需要實現:

      • 雜湊函式,需要實現一個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;
        }