How to initialize an unordered_set in C++11

In this article we will discuss the different ways to initialize an unordered_set.

Creating an empty unordered_set and then inserting elements in it is easy. But its not the practical scenario always. Many times we need to initialize an unordered_set while creation. For that it provides different overloaded constructors and we will use some of them to initialize an unordered_set from an another datastructure i.e.

Initializing an unordered_set from an array

unordered_set provides a constructor that accepts a range of iterators and try to insert all elements in while iterating from start to end of range i.e.

// Array of int
int arr[] = {2,4,6,1,3,6,8,3,2};

// Create an unoredered set and initialize it with the array
// Set will contain only unique elements
std::unordered_set<int> setOfNum(arr, arr + sizeof(arr)/sizeof(int));

Above set will contain only unique elements from array and store them in arbitrary order.

Initializing an unordered_set by an initialzer list

unordered_set provides a constructor that accepts an initialzer_list as an argument and initialize the set with them i.e.

// Create an unoredered set and initialize it initializer_list
std::unordered_set<int> setOfNum2({1,2,3,1,3,4,2});

Initializing an unordered_set with a vector

For this we will use the same constructor of unordered_set that accepts a range of iterators and initialize set with all elements in range i.e.

std::vector<int> vec({14,5,6,7});

// Create an unoredered set and initialize it with vector
std::unordered_set<int> setOfNum3(vec.begin(), vec.end());

Complete Working example is as follows,

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

int main() {

	// Array of int
	int arr[] = { 2, 4, 6, 1, 3, 6, 8, 3, 2 };

	// Create an unoredered set and initialize it with the array
	// Set will contain only unique elements
	std::unordered_set<int> setOfNum(arr, arr + sizeof(arr) / sizeof(int));

	// Iterate over the set and display contents
	for (int val : setOfNum)
		std::cout << val << "  ";
	std::cout << std::endl;

	// Create an unoredered set and initialize it initializer_list
	std::unordered_set<int> setOfNum2( { 1, 2, 3, 1, 3, 4, 2 });

	// Set will contain only unique elements
	// Iterate over the set and display contents
	for (int val : setOfNum2)
		std::cout << val << "  ";
	std::cout << std::endl;

	std::vector<int> vec( { 14, 5, 6, 7 });
	// Create an unoredered set and initialize it with vector
	std::unordered_set<int> setOfNum3(vec.begin(), vec.end());

	// Set will contain only unique elements
	// Iterate over the set and display contents
	for (int val : setOfNum3)
		std::cout << val << "  ";
	std::cout << std::endl;

}

Output:

8  3  1  6  4  2  
4  3  2  1  
7  6  5  14  

 

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top