Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tạo unordered_map của pair trong C++


Trong hướng dẫn này, ta sẽ thảo luận chương trình để hiểu cách tạo unordered_map của pair trong C++.

Unordered_map mặc định không có hàm băm cho pair. Nếu muốn giá trị băm cho một pair cụ thể, cần truyền hàm băm một cách tường minh.

Ví dụ

#include <bits/stdc++.h>
using namespace std;

struct hash_pair {
    template <class T1, class T2>
    size_t operator()(const pair<T1, T2>& p) const {
        auto hash1 = hash<T1>{}(p.first);
        auto hash2 = hash<T2>{}(p.second);
        return hash1 ^ hash2;
    }
};

int main() {
    unordered_map<pair<int, int>, bool, hash_pair> um;
    pair<int, int> p1(1000, 2000);
    pair<int, int> p2(2000, 3000);
    pair<int, int> p3(2005, 3005);
    um[p1] = true;
    um[p2] = false;
    um[p3] = true;
    cout << "Contents of the unordered_map : \n";
    for(auto p : um)
        cout << "[" << p.first.first << ", " << p.first.second << "] ==> " << p.second << "\n";
    return 0;
}

Kết quả

Contents of the unordered_map :
[1000, 2000] ==> 1
[2005, 3005] ==> 1
[2000, 3000] ==> 0