Search code examples
c++stlunordered-set

How to initialize unordered_set with default value 0 or -1?


How could I initialize the STL unordered_set with default value 0 or -1 without for loop init like how we do with an array,

int arr[10] = {0};

Solution

  • You probably confuse sets and arrays/vectors here:

    A std::set or std::unordered_set only holds unique values. It can never contain any value more than once.

    If you just want to initialize it with some values, you can do it likewise to an array:

    • std::unordered_set<int> set{0, -1}; creates a set with two values: 0 and -1

    • std::unordered_set<int> set{0, -1, -1, -1, -1}; does the same, since each unique value will only be contained once.