如何在C++中创建自定义类的unordered_map
unordered_map用于实现哈希表。它存储键值对。对于每个键,都会计算一个哈希函数,并在该哈希条目中存储值。标准数据类型(int,char,string等)的哈希函数是预定义的。如何使用自己的数据类型来实现哈希表?
unordered_map允许使用第三个参数来指定我们自己的哈希函数。
// 使用KeyType、ValueType和MyHashType定义的哈希函数创建unordered_map
unordered_map<KeyType, ValueType, MyHashType> um;
这里的MyHashFunction是一个必须包含 操作符函数 () 的类或结构体。
我们还必须在我们自己的类中实现 操作符 == ,以处理冲突。
下面是一个示例代码,其中Person类的对象用作键。我们定义自己的哈希函数,它将姓和名字的长度总和用作哈希表中的键。请注意,此代码的目的仅是演示使用简单代码的工作方式,长度总和可能不是哈希函数的好主意。
//演示unordered_map用于自定义数据类型的工作原理的CPP程序。
#include <bits/stdc++.h>
using namespace std;
//此类的对象用作哈希表中的键。它必须实现operator ==()以处理冲突。
struct Person {
string first, last; // 姓和名
Person(string f, string l)
{
first = f;
last = l;
}
// 在冲突的情况下匹配姓和名。
bool operator==(const Person& p) const
{
return first == p.first && last == p.last;
}
};
class MyHashFunction {
public:
// 使用名字的长度之和作为哈希函数。
size_t operator()(const Person& p) const
{
return p.first.length() + p.last.length();
}
};
// 驱动程序
int main()
{
unordered_map<Person, int, MyHashFunction> um;
Person p1("kartik", "kapoor");
Person p2("Ram", "Singh");
Person p3("Laxman", "Prasad");
um[p1] = 100;
um[p2] = 200;
um[p3] = 100;
for (auto e : um) {
cout << "[" << e.first.first << ", "
<< e.first.last
<< "] = > " << e.second << '\n';
}
return 0;
}
输出:
[Laxman, Prasad] = > 100
[kartik, kapoor] = > 100
[Ram, Singh] = > 200
另一个示例,其中使用预定义哈希类的预定义操作符函数来创建我们的总哈希表。
// CPP程序演示unordered_map对用户自定义数据类型的工作原理。
#include <bits/stdc++.h>
using namespace std;
struct Person {
string first, last;
Person(string f, string l)
{
first = f;
last = l;
}
bool operator==(const Person& p) const
{
return first == p.first && last == p.last;
}
};
class MyHashFunction {
public:
// 我们使用字符串的预定义哈希函数
// 并将我们的哈希函数定义为哈希值的XOR。
size_t operator()(const Person& p) const
{
return (hash<string>()(p.first)) ^
(hash<string>()(p.last));
}
};
// 驱动程序
int main()
{
unordered_map<Person, int, MyHashFunction> um;
Person p1("kartik", "kapoor");
Person p2("Ram", "Singh");
Person p3("Laxman", "Prasad");
um[p1] = 100;
um[p2] = 200;
um[p3] = 100;
for (auto e : um) {
cout << "[" << e.first.first << ", "
<< e.first.last
<< "] = > " << e.second << '\n';
}
return 0;
}
输出:
[Laxman, Prasad] = > 100
[kartik, kapoor] = > 100
[Ram, Singh] = > 200