C++ Initialize an Unordered Set

www‮figi.‬tidea.com

In C++, you can initialize an unordered set using an initializer list or by copying from another container. Here are some examples:

#include <iostream>
#include <unordered_set>

int main() {
  // Initialize an unordered set using an initializer list
  std::unordered_set<int> mySet1 = {1, 2, 3, 4, 5};

  // Initialize an unordered set by copying from another container
  std::vector<int> vec = {6, 7, 8, 9, 10};
  std::unordered_set<int> mySet2(vec.begin(), vec.end());

  // Print the contents of the unordered sets
  std::cout << "mySet1: ";
  for (const auto& elem : mySet1) {
    std::cout << elem << " ";
  }
  std::cout << std::endl;

  std::cout << "mySet2: ";
  for (const auto& elem : mySet2) {
    std::cout << elem << " ";
  }
  std::cout << std::endl;

  return 0;
}

In this example, we create two unordered sets mySet1 and mySet2. mySet1 is initialized using an initializer list, and mySet2 is initialized by copying elements from a vector using the constructor that takes two iterators. We then use a ranged for loop to print the contents of both sets.

The output of this program is:

mySet1: 5 4 3 2 1 
mySet2: 6 7 8 9 10

As you can see, both sets are initialized correctly and their contents are printed in no particular order.