如何在 C++ 中创建自定义类或结构的无序集?
在本教程中,我们将讨论一个程序来了解如何在 C++ 中创建自定义类或结构的无序集。
为此,我们将创建一个结构类型,然后使用用户定义的函数比较两个结构类型以存储哈希函数。
示例
#include <bits/stdc++.h>
using namespace std;
//defined structure
struct Test {
int id;
bool operator==(const Test& t) const{
return (this->id == t.id);
}
};
//defined class for hash function
class MyHashFunction {
public:
size_t operator()(const Test& t) const{
return t.id;
}
};
int main(){
Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };
//defining unordered set
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP