如何在C ++中创建用户定义的类或结构的unordered_set?
在本教程中,我们将讨论一个程序,以了解如何在C++中创建用户定义的类或结构的无序集合。
为此,我们将创建一个结构类型,然后将两种结构类型与用户定义的函数进行比较以存储哈希函数。
示例
#include <bits/stdc++.h>
using namespace std;
//定义的结构
struct Test {
int id;
bool operator==(const Test& t) const{
return (this->id == t.id);
}
};
//为哈希函数定义的类
class MyHashFunction {
public:
size_t operator()(const Test& t) const{
return t.id;
}
};
int main(){
Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };
//定义无序集
unordered_set<Test, MyHashFunction> us;
us.insert(t1);
us.insert(t2);
us.insert(t3);
us.insert(t4);
for (auto e : us) {
cout << e.id << " ";
}
return 0;
}输出结果
115 101 110 102