C++ unordered set – Initialize set c++ – How to Initialize an Unordered_Set in C++

Initialize set c++: Since the value of an element defines it, sets are a form of associative container in which each element must be special. The element’s value cannot be changed after it has been added to the set, but the element’s modified value can be removed and added again.

A hash table is used to implement an unordered set, with keys hashed into hash table indices to ensure that insertion is always random. All operations on the unordered set take constant time O(1) on average, which can go up to linear time O(n) in the worst case depending on the internally used hash function, but they perform very well in practise and generally provide a constant time lookup operation.

Initialize an Unordered Set

C++ unordered set example: There are 3 ways to initialize an unordered set in c++.

Method #1:Initialize from an array

C++ set initialization: The constructor of an unordered set takes a list of iterators and tries to insert all elements while iterating from the beginning to the end of the range.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{

    // integer array
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 3 };
    // first we create a unordered set and initialize with
    // array
    std::unordered_set<int> arrayset(
        array, array + sizeof(array) / sizeof(int));
    // printing the set
    for (int value : arrayset)
        std::cout << value << "  ";

    return 0;
}

Output:

9  8  7  6  5  4  3  2  1

Method #2:Initialize by an initializer list

C++ unordered_set: unordered set has a constructor that takes an initialzer list as an argument and uses it to initialise the set.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{

    //  initialize the set with the initializer_list
    std::unordered_set<int> arrayset(
        { 1, 2, 3, 4, 5, 6, 7, 12, 3, 9, 5 });
    // printing the set
    for (int value : arrayset)
        std::cout << value << "  ";

    return 0;
}

Output:

9  12  7  6  5  4  3  2  1

Method #3:Initialize from vector

C++ unordered set: We’ll use the same unordered set function constructor that accepts a range of iterators to initialize set with all elements in range.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // given vector
    std::vector<int> vec({ 1, 5, 9, 2, 3, 6, 3, 7, 8 });
    // initialize the set from vector
    std::unordered_set<int> arrayset(vec.begin(),
                                     vec.end());
    // printing the set
    for (int value : arrayset)
        std::cout << value << "  ";

    return 0;
}

Output:

8  7  6  3  2  9  5  1

Related Programs: