In this article we will discuss how to use std::unordered_set with User defined classes.

std::unordered_set internally implements a hash table to store the elements. To know more about Hash Table visit the following article, What is Hashing and Hash Table?

std::unordered_set uses the hasher and comparison function. For primitive data types like int, string etc. default hasher anc comparision functions will work i.e.

  • std::hash<T>()
  • std::equal_to<T>

But for User defined Objects, these default implementations will not work. We need to provide some extra to make this default functions work.

There are 2 ways to make an unordered_set of User Define Types / Classes i.e.

  • Create special functions to make default std::hash<> & std::equals_to<> functions to work with User Defined classes
  • Creating Custom Hasher and Comparision Functors and pass it to unordered_set.

Lets see them one by one. But, first create a Student class i.e.

Unordered_set of User Defined Class with default Hasher & Comparision Function

Lets create an unordered_set of type Student taht should store unique Student objects based on ID.

Here, we have not provided any Custom Hasher or Comparision function hence default hasher and comparison function will be used i.e.

Default Hasher Function for class Student

std::hash<Student>(const Student & obj);

Default Comparison Function for class Student 

std::equals_to<Student>(const Student & obj1,const Student & obj2 );

This will internally class the == operator() function.

So, to make this unordered_set<Student> work, we need to implement the above hasher and == operator for class Student.

Implementing std::hash<Student>,

It will compute the hash on only member variable ID for an object of class Student.

Implementing == operator for class Student,

This will compare the ID only to check if two objects of class Student are equal or not i.e.

Now we can use the std::unordered_set of type Student with default hasher and comparator i.e.

The above Unordered Set will store elements with unique size only.Now, suppose a new requirement comes and we also want to store objects in a new unoredered_set with uniwue names instead of unique ID. How to do that?

unordered_set of User Defined Class with Custom Hasher and Comparator

As, now we need to create a new unordered_set of type Student that can store unique Student objects based on name instead of ID, so we can not use the above implementation of std::hash<Student> and operator==.

 

So, to achieve this we can create custom Hasher and Comparator.

Custom Hasher for class Student

It will compute the hash based on name of Student,

Custom Comparator for class Student,

It will compare the two Student objects based on name instead of ID i.e.

Now lets use these Custom Functors

This set will store the unique student objects based on name only.

Complete working Example is as follows,

Output: