如何在 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