Search code examples
c++vectorinitializationdeclarationunordered-set

insert vector into unordered set after declaration c++


I'm looking for a way to insert a vector of elements into an unordered set that I have already declared. Say I have code as follows:

unordered_set<string> us;
vector<string> v{"green", "dog", "keys"};

Here, us has already been declared. How can I populate us with the elements in vector v with one command (i.e. without a for loop and pushing the elements individually) after its declaration?

This similar answer adding elements of a vector to an unordered set is not what I'm looking for as the unordered set is initialized during declaration.

Better yet, is it possible to populate the unordered set with multiple elements in one command without using a vector?


Solution

  • Use an iterator with insert().

    us.insert(v.cbegin(), v.cend());
    

    No need for the vector as long as the sequence conforms to the input iterator concept and returns strings. An array, other set, vector, etc. are all fine.