如何在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 开工红包祝福语毕业简短