Unordered Set in C++ (STL)

std::unordered_set is an STL container and its introduced in C++11. It provides a functionality of a Set i.e. it can contains the unique elements only. unordered_set stores the elements internally using a Hash Table.

We can declare an unordered_set of a particular type only i.e.

std::unordered_set<T> setOfTypeT;

Elements of Type with which an unoredered_set is declared can only be added in it. Also, all elements of Type T should be,

  • Copyable or Movable
  • Comparable

Above requirements are because of the reason that element added in unordered_set will act as both key and value for internal Hash Table. As it’s a key therefore it should be comparable and copy-able.

Also, all elements in the unordered_set are immutable i.e. they can not be modified once inserted. They can only be deleted after the insertion.

Header File Required is,



    #include <unordered_set>

    Creating and using an std::unordered_set of std::string

    As all objects of type std::string is copy-able and comparable. So, let’s create an unordered_set of type std::string and use it i.e.

    std::unordered_set<std::string> setOfStrs;

    Here, as we have declared an unordered set of type std::string. It means it can only store unique strings. Let’s see a complete example,

    #include <iostream>
    #include <unordered_set>
    #include <algorithm>
    
    int main() {
    
    	// Creating an Unoredered_set of type string
    	std::unordered_set<std::string> setOfStrs;
    
    	// Insert strings to the set
    	setOfStrs.insert("First");
    	setOfStrs.insert("second");
    	setOfStrs.insert("third");
    
    	// Try to Insert a duplicate string in set
    	setOfStrs.insert("second");
    
    	// Iterate Over the Unordered Set and display it
    	for (std::string s : setOfStrs)
    		std::cout << s << std::endl;
    
    }
    

    Output:

    third
    second
    First
    

    Here we added 4 elements in the unoredered_set but only 3 will get added, last insertion will not work because “second” is already inserted in set and unoredered_set contains only the unique elements.

    [showads ad=inside_post]

     

    Thanks.

     

    Scroll to Top