如何在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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语