如何在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 送给学长毕业祝福语简短