Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create an unordered_set of user defined class or struct in C++?
In this tutorial, we will be discussing a program to understand how to create an unordered set of user defined class or struct in C++.
For this we will create a structure type and then compare two structure types with the function defined by the user to store the hash function.
Example
#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;
}
Output
115 101 110 102
Advertisements