
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- How to create an unordered_map of user defined class in C++?
- How to create user defined exceptions in C#?
- When should we create a user-defined exception class in Java?
- How to create a user defined exception (custom exception) in java?
- User Defined Literals in C++
- C/C++ Struct vs Class
- User-defined Custom Exception in C#
- How to implement user defined exception in Python?
- What are user-defined exceptions in C#?
- User-defined Exceptions in C# with Example
- How to create a Struct Instance Using a Struct Literal in Golang?
- What are user defined data types in C#?
- 2D vector in C++ with user defined size
- C++ set for user defined data type?
- User-Defined Exceptions in Python

Advertisements