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
Asked
Active
Viewed 4.2k times
46
2 Answers
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 – 101is5 Sep 18 '22 at 12:33s(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.
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
-
`std::inserter` is required to insert into an associative container. – James McNellis Oct 12 '12 at 01:22
-
-
2does s.end() remain valid even if the container rehashes? – Johannes Schaub - litb Dec 09 '14 at 13:39
-