adding elements of a vector to an unordered set
Asked Answered
L

2

48

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

Little answered 12/10, 2012 at 1:17 Comment(0)
M
65

If you're constructing the unordered_set then:

std::vector<int> v;
std::unordered_set<int> s(v.begin(), v.end());
Mirtamirth answered 12/10, 2012 at 1:28 Comment(1)
what should be done next? I've tried this, but it doesn't seem to build the set. E.g. vector<int> v; set<int> 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.Subscript
E
29

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()));
Emaciated answered 12/10, 2012 at 1:21 Comment(4)
std::inserter is required to insert into an associative container.Drucilladrucy
yup, i knew i missed something, fixed.Emaciated
does s.end() remain valid even if the container rehashes?Selry
if v is empty then an 0 will be added to s!Gildea

© 2022 - 2024 — McMap. All rights reserved.