
- 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_map of user defined class in C++?
In this tutorial, we will be discussing a program to understand how to create an unordered map of user defined class in C++.
To create an unordered map from a user defined class, we will pass the hash function as the class method being the third argument.
Example
#include <bits/stdc++.h> using namespace std; //objects of class to be used as key values struct Person { string first, last; Person(string f, string l){ first = f; last = l; } bool operator==(const Person& p) const{ return first == p.first && last == p.last; } }; class MyHashFunction { public: //using sum of length as hash function size_t operator()(const Person& p) const{ return p.first.length() + p.last.length(); } }; int main(){ unordered_map<Person, int, MyHashFunction> um; Person p1("kartik", "kapoor"); Person p2("Ram", "Singh"); Person p3("Laxman", "Prasad"); um[p1] = 100; um[p2] = 200; um[p3] = 100; for (auto e : um) { cout << "[" << e.first.first << ", "<< e.first.last<< "] = > " << e.second << '\n'; } return 0; }
Output
[Laxman, Prasad] = > 100 [kartik, kapoor] = > 100 [Ram, Singh] = > 200
- Related Articles
- How to create an unordered_set of user defined class or struct in C++?
- How to create an unordered_map of pairs 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++
- 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
- 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
- PHP User-defined functions

Advertisements