C++ STL Unordered Set – std::unordered_set

In this tutorial you will learn about stl unordered set container in c++ and various functions applicable on it.

Unordered Set comes under unordered containers. As we discussed in introduction to stl article, unordered containers internally implemented with hash tables. Each item calculated by hash function, to map to hash table. The main advantage is if we have effective hash function we can find elements in O (1) time. On average it can go to linear time. Simply we can say it’s based on type of hash function used.

So we can say these are fastest among all containers.

As name says that in unordered_set the order is not defined. Unordered set doesn’t allow duplicates.

C++ STL Unordered Set – std::unordered_set

Useful iterators to work on this unordered set:

begin(): returns iterator to the beginning

end(): returns iterator to the end of the list

cbegin(): returns constant iterator to the beginning

cend(): returns constant iterator to the end.

First we need to include unordered_set header file. Which is #include<unordered_set>

Inserting element into unordered_set:

There are various ways to insert elements into unordered_set.

Method 1: Insert directly by passing element.

UnOrdSet.insert(element);

Method 2: Using iterator. This returns iterator at inserted position.

UnOrdSet.insert ( iterator, value)

Method 3: Copying from another container.

Example program to insert into unordered_set:

Output

56 45 34 23 40 99 0 10 20 30

Modifiers: The functions which effect size/data of that container

erase(): We can erase an element by specifying value or pointing to iterator.

swap(): swaps elements of Unordered_set1 to Unorderedset2 and Unorderedset2 to Unordered_set1.

clear(): removes all elements in the list. It results list of size 0.

Example program to show above functions:

Output

elements after deleting 12 –>14 10 11 13
unordered_set 1 elements before swapping –>14 10 11 13
unordered_set 2 elements before swapping –>3 2 1 0
unordered_set 1 elements after swapping –>3 2 1 0
unordered_set 2 elements after swapping –>14 10 11 13
Performing clear() operation on unordered_set1……
Unordered_set is empty

Information retrieving functions:

empty(): returns a Boolean value whether Unordered_set is empty or not.

size(): returns the size of the Unordered_set.

max_size(): returns the maximum size a Unordered_set can have.

And some more operations are:

find(): It returns iterator to the element.

count(x):  Returns how many times elements “x” present in Unordered_set.

Example program to show above functions:

Output

unordered_set is not empty
size of the unordered_set is 5
maximum size of the unordered_set is 1152921504606846975
finding elemnt 12 in unordered_set
12
22 is not in the unordered_set

Leave a Reply

Your email address will not be published. Required fields are marked *