46

Is there an easy way to add all the elements of a vector to an unordered_set? They are of the same type. Right now, I am using a for loop and was wondering if there is a better way to do it

chema989
  • 3,962
  • 2
  • 20
  • 33
jamesatha
  • 7,280
  • 14
  • 37
  • 54

2 Answers2

63

If you're constructing the unordered_set then:

std::vector<int> v;
std::unordered_set<int> s(v.begin(), v.end());
mythagel
  • 1,789
  • 19
  • 15
  • what should be done next? I've tried this, but it doesn't seem to build the set. E.g. ```vector v; set s(v.begin(), v.end()); for(...) // here I push back elements for( auto i : s) cout << i;``` doesn't print anything, and debugging shows the set is empty. – 101is5 Sep 18 '22 at 12:33
27

Forgive me if my syntax has any minor bugs, but you can try the std::copy function, its meant for this purpose.

std::vector<int> v;
std::unordered_set<int> s;
std::copy(v.begin(),v.end(),std::inserter(s,s.end()));
Karthik T
  • 31,456
  • 5
  • 68
  • 87