Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีสร้าง unordered_map ของคู่ (pair) ใน C++


ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อทำความเข้าใจวิธีสร้าง unordered map ของคู่ (pair) ใน C++

Unordered maps เป็น map ที่ไม่มีฟังก์ชันแฮชสำหรับ pair โดยค่าเริ่มต้น หากเราต้องการค่าแฮชสำหรับ pair เฉพาะ จำเป็นต้องส่งผ่านอย่างชัดเจน

ตัวอย่าง

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

// to hash any given pair
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() {
    // explicitly sending hash function
    unordered_map<pair<int, int>, bool, hash_pair> um;
    // creating some pairs to be used as keys
    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;
}

เอาต์พุต

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