How to create an unordered_set of user defined class or struct in C++? Last Updated : 22 Nov, 2021 Comments Improve Suggest changes Like Article Like Report The unordered_set internally implements a hash table to store elements. By default we can store only predefined type as int, string, float etc. If we want to store the element of user defined type as structure then compiler will show an error because before storing elements into unordered_set compiler performs some checking. And while comparing two user defined type compiler can not compare them hence it generate an error. So, in order to store a structure in a unordered_set, some comparison function need to be designed. Since unordered_set also store implements hash table to store elements we should also have to implement hash function to perform hashing related work. Below method explains its implementation. Implementation: We create a structure type and define a comparison function inside that structure that will used to compare two structure type objects. Since unordered_set internally implements hash function so we should have also implement the hash function for user defined type objects. Syntax To store user defined type elements unordered_set should follow following syntax unordered_set(elementType, MyHashType) us; // element type is user defined type and MyHashType is class implementing hash function Below code explains it. CPP // CPP implementation to use // user-defined data type in // structures #include <bits/stdc++.h> using namespace std; // Structure definition struct Test { int id; // This function is used by unordered_set to compare // elements of Test. bool operator==(const Test& t) const { return (this->id == t.id); } }; // class for hash function class MyHashFunction { public: // id is returned as hash function size_t operator()(const Test& t) const { return t.id; } }; // Driver method int main() { // put values in each // structure define below. Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // define a unordered_set having // structure as its elements. unordered_set<Test, MyHashFunction> us; // insert structure in unordered_set us.insert(t1); us.insert(t2); us.insert(t3); us.insert(t4); // printing the elements of unordered_set for (auto e : us) { cout << e.id << " "; } return 0; } Output: 115 101 110 102 Output: 115 101 110 102 Below is another example where we use predefined hash functions to make overall hash function of our defined class. CPP // CPP program to demonstrate working of unordered_set // for user defined data types. #include <bits/stdc++.h> using namespace std; 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: // We use predefined hash functions of strings // and define our hash function as XOR of the // hash values. size_t operator()(const Person& p) const { return (hash<string>()(p.first)) ^ (hash<string>()(p.last)); } }; // Driver code int main() { unordered_set<Person, MyHashFunction> us; Person p1("kartik", "kapoor"); Person p2("Ram", "Singh"); Person p3("Laxman", "Prasad"); us.insert(p1); us.insert(p2); us.insert(p3); for (auto e : us) { cout << "[" << e.first << ", " << e.last << "]\n"; } return 0; } Output: [Laxman, Prasad] [kartik, kapoor] [Ram, Singh] Comment More infoAdvertise with us Next Article set vs unordered_set in C++ STL ankit15697 Follow Improve Article Tags : C++ STL cpp-unordered_set Practice Tags : CPPSTL Similar Reads Unordered Sets in C++ STL In C++, unordered_set is an unordered associative container that stores unique elements. Unlike set, it stores its elements using hashing. This provides average constant-time O(1) search, insert, and delete operations but the elements are not sorted in any particular order.Example:C++#include <io 6 min read Different Ways to Initialize an unordered_set in C++ An unordered_set is an associated container available in the C++ Standard Template Library(STL) that is used for unique elements without any specific ordering, it internally uses the working principle of a hashtable to store elements. Different ways to Initialize an unordered_set in C++ Initializati 6 min read Commonly Used Methodsunordered_set begin() function in C++ STLThe unordered_set::begin() method is a builtin function in C++ STL which is used to return an iterator pointing to the first element in the unordered_set container. All of the iterators of an unordered_set can be used to only access the elements, iterators are not allowed to modify elements present 2 min read unordered_set end() in C++ STLThe unordered_set::end() function is a built-in function in C++ STL which returns an iterator pointing to the past-the-end-element. This iterator does not directly point to an element, rather it points to the location just after the last element. Syntax umap_name.end() or, umap_name.end(int i) Param 2 min read unordered_set size() function in C++ STLThe unordered_set::size() method is a builtin function in C++ STL which is used to return the number of elements in the unordered_set container. Syntax: unordered_set_name.size() Parameter: It does not accepts any parameter. Return Value: The function returns the number of elements in the container. 1 min read unordered_set empty() function in C++ STLThe unordered_set::empty is a built-in function in C++ STL which is used to check if an unordered_set container is empty or not. It returns True if the unordered_set container is empty, otherwise it returns False. Syntax: set_name.empty()Parameters: This function does not accepts any parameter. Retu 2 min read unordered_set insert() function in C++ STLThe unordered_set::insert() is a built-in function in C++ STL which is used to insert a new {element} in the unordered_set container. Each element is inserted only if it is not already present in the container (elements in an unordered_set have unique values). The insertion is done automatically at 3 min read unordered_set emplace() function in C++ STLThe unordered_set::emplace() function is a built-in function in C++ STL which is used to insert an element in an unordered_set container. The element is inserted only if it is not already present in the container. This insertion also effectively increases the container size 1.Syntax: unordered_set_n 2 min read unordered_set find() function in C++ STLThe unordered_set::find() function is a built-in function in C++ STL which is used to search for an element in the container. It returns an iterator to the element, if found else, it returns an iterator pointing to unordered_set::end(). Syntax : unordered_set_name.find(key)Parameter: This function a 2 min read unordered_set count() function in C++ STLThe unordered_set::count() function is a built-in function in C++ STL which is used to count occurrences of a particular element in an unordered_set container. As the unordered_set container does not allows to store duplicate elements so this function is generally used to check if an element is pres 2 min read unordered_set erase() function in C++ STLThe unordered_set::erase() function is a built-in function in C++ STL which is used to remove either a single element or a group of elements ranging from start(inclusive) to end(exclusive). This decreases the size of a container by the number of elements removed.Note: Buckets in unordered_set are nu 3 min read unordered_set swap() in C++ STLThe swap() method of âunordered_setâ swaps the contents of two containers. It is public member function. This function: Exchanges the content of the container by the content of variable, which is another unordered_set object containing elements of the same type but the sizes may differ. After the ca 3 min read unordered_set bucket() function in C++ STLThe unordered_set::bucket() method is a builtin function in C++ STL which returns the bucket number of a specific element. That is, this function returns the bucket number where a specific element is stored in the unordered_set container. The bucket is a slot in the unordered_set's internal hash tab 2 min read Other Member Methodsunordered_set reserve() function in C++ STLThe unordered_set::reserve() method is a builtin function in C++ STL which is used to request capacity change of unordered_set. It sets the number of buckets in the container to contain at least n elements. If n is greater than the current bucket_count multiplied by the max_load_factor, the containe 2 min read unordered_set max_size() in C++ STLThe unordered_set::max_size() is a built-in function in C++ STL, defined in <unordered_set.h> which returns maximum number of elements that an unordered_set container can hold(i.e the maximum size of the unordered_set) due to system constraints or internal implementation . Syntax: map_name.max 1 min read unordered_set max_bucket_count() function in C++ STLThe unordered_set::max_bucket_count() is a built-in function in C++ STL which is used to find the maximum number of buckets that unordered_set can have. This function returns the maximum number of buckets a system can have because of the constraints specified by the system and some limitations. Para 2 min read unordered_set max_load_factor() in C++ STLunordered_set::max_load_factor() is a function in C++ STL which returns(Or sets) the current maximum load factor of the unordered set container. The load factor is the ratio between number of elements in the container and number of buckets(bucket_count). By default the maximum load factor of an unor 2 min read unordered_set load_factor() function in C++ STLThe unordered_set::load_factor() is a built-in function in C++ STL which returns the current load factor in the unordered_set container. The load factor is the ratio between the number of elements in the container (its size) and the number of buckets (bucket_count): load_factor = size / bucket_count 3 min read unordered_set bucket_size() in C++ STLThe unordered_set::bucket_size() function is a built-in function in C++ STL which returns the total number of elements present in a specific bucket in an unordered_set container.The bucket is a slot in the unordered_set's internal hash table where elements are stored.Note: Buckets in unordered_set a 2 min read unordered_set bucket_count() function in C++ STLThe unordered_set::bucket_count() method is a builtin function in C++ STL which returns the total number of buckets present in an unordered_set container. The bucket is a slot in the unordered_set's internal hash table where elements are stored. Note: Buckets in unordered_set are numbered from 0 to 2 min read unordered_set hash_function() in C++ STLThe unordered_set::hash_function() is a built-in function in C++ STL which is used to get hash function. This hash function is a unary function which takes asingle argument only and returns a unique value of type size_t based on it. Syntax: unordered_set_name.hash_function() Parameter: The function 1 min read unordered_set emplace_hint() function in C++ STLThe unordered_set::emplace_hint() function is an inbuilt function in C++ STL which inserts a new element in the unordered_set only if the value to be inserted is unique, with a given hint. Syntax: unordered_set_name.emplace_hint( position, value ) Parameter: This function accepts two parameters as m 2 min read unordered_set equal_range in C++ STLequal_range() in general returns range that includes all elements equal to given value. For unordered_set where all keys are distinct, the returned range contains at-most one element. Syntax setname.equal_range(key name) Arguments It takes the key to be searched as parameter. Return Value It returns 2 min read unordered_set operators in C++ STLUnordered_set provides two operators in C++ STL. These are:Â Syntax:Â Â 1. (unordered_set &lhs == unordered_set &rhs) 2. (unordered_set &lhs != unordered_set &rhs) These operators are discussed in detail below:Â unordered_set == operator in C++ STL The â==â is an operator in C++ STL pe 5 min read unordered set of Vectors in C++ with Examples What is an unordered set? In C++, an unordered set is an unordered container that can hold a number of unique elements. Unlike a set, elements in an unordered set are not arranged in any particular order. Internally, an unordered set is implemented using a hash table where keys are hashed into indic 6 min read unordered set of Pairs in C++ with Examples What is pair? Utility header in C++ provides us pair container. A pair consists of two data elements or objects. The first element is referenced as âfirstâ and the second element as âsecondâ and the order is fixed (first, second).Pair is used to combine together two values that may be different in t 5 min read How to create an unordered_set of user defined class or struct in C++? The unordered_set internally implements a hash table to store elements. By default we can store only predefined type as int, string, float etc. If we want to store the element of user defined type as structure then compiler will show an error because before storing elements into unordered_set compil 3 min read set vs unordered_set in C++ STL Differences : | set | unordered_set --------------------------------------------------------- Ordering | increasing order | no ordering | (by default) | Implementation | Self balancing BST | Hash Table | like Red-Black Tree | search time | log(n) | O(1) -> Average | | O(n) -> Worst Case Insert 4 min read Like