如何在 C++ 中建立一個成對的無序對映?
本教程中,我們將討論一個程式以瞭解如何在 C++ 成對建立無序對映。
無序對映預設情況下不包含成對的雜湊函式。如果我們需要特定成對的雜湊值,則需要明確傳遞。
示例
#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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP