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
adding elements of a vector to an unordered set
Asked Answered
If you're constructing the unordered_set then:
std::vector<int> v;
std::unordered_set<int> s(v.begin(), v.end());
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()));
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.
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