adding elements of a vector to an unordered set

32,555

Solution 1

If you're constructing the unordered_set then:

std::vector<int> v;
std::unordered_set<int> s(v.begin(), v.end());

Solution 2

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()));
Share:
32,555
jamesatha
Author by

jamesatha

Updated on July 09, 2022

Comments

  • jamesatha
    jamesatha almost 2 years

    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

  • James McNellis
    James McNellis over 11 years
    std::inserter is required to insert into an associative container.
  • Karthik T
    Karthik T over 11 years
    yup, i knew i missed something, fixed.
  • Johannes Schaub - litb
    Johannes Schaub - litb over 9 years
    does s.end() remain valid even if the container rehashes?
  • James Harper
    James Harper almost 9 years
    if v is empty then an 0 will be added to s!