std::unordered_set Basic Usage & Example

How to create and use an std::unordered_set of std::string.

Unordered_set: In this article we will discuss about what is unordered set, how to create an unordered set and how to use it. So, let’s start exploring the topic.

std::unordered_set :

Unordered_set: In C++11, this std::unordered_set was introduced which is an STL container. It provides the functionality same as the set means all the elements contained inside it are unique. Internally the elements are stored using a Hash Table.

An unordered set can be declared for a particular type only. Like this

std::unordered_set<T> setOfTypeT;

where,

  • T defines the type of elements the string can accept.
  • All elements of type T should be copyable and comparable.
  • All elements in it are immutable means can not be modified after insertion.

To use unordered_set we have to include the header file i.e

#include <unordered_set>

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

Let’s see a program to create an unordered_set of type std::string and use it

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

It means it store only elements of string type.

#Program : 

#include <iostream> 
#include <unordered_set> 
#include <algorithm> 

int main() 
{ 
// Unoredered_set of type string is created 
std::unordered_set<std::string> setOfStrs; 

// Inserting strings to the set 
setOfStrs.insert("Hyderabad"); 
setOfStrs.insert("Bhubaneswar"); 
setOfStrs.insert("Kolkata"); 

// Trying to Insert a duplicate string in set i.e 'Kolkata' 
setOfStrs.insert("Kolkata"); 

// Iterating Over the Unordered Set and displaying it 
for (std::string s : setOfStrs) 
    std::cout << s << std::endl; 
}
Output :
Bhubaneswar
Hyderabad
Kolkata

In the example, we saw that we tried to insert 4 string elements. But only 3 string elements inserted successfully. Because the unordered_set does not accept duplicate element. So the last element which we tried to insert that did not insert into it.