如何在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 同事除夕加班祝福语简短