如何在C ++中创建成对的unordered_map?
在本教程中,我们将讨论一个程序,以了解如何在C++中创建对的无序映射。
默认情况下,无序映射是对不包含哈希函数的映射。如果我们想要特定对的哈希值,则需要显式传递它。
示例
#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;
}输出结果
Contents of the unordered_map : [1000, 2000] ==> 1 [2005, 3005] ==> 1 [2000, 3000] ==> 0