Search code examples
stlc++17stdvectorstl-algorithmmultiset

Copy contents of a vector into a multiset


I've tried copying the contents of a std::vector into a std::multiset like this:

std::vector<unsigned> v(32768);
std::generate(v.begin(), v.end(), rand);

std::multiset<unsigned> m(v.begin(), v.end());

However, that only copies over the indexes 0-32768 and not the valuesContents of the multiset

How do you copy the values in a std::vector into a std::multiset?


Solution

  • However, that only copies over the indexes 0-32768 and not the values

    Are you sure?

    From the screenshot you reported, seems to me that you have

    0 1 3 4 6 6 6 ...
    

    Think a little what you obtain copying a std::vector in a std::multiset: you get the same number re-ordered.

    So generating 32768 random number, you've obtained a 0, a 1, no 2, a 3, a 4, three or more 6.

    In the vector are in really different positions; in the multi-set they are at the beginning so you can think you've copied the indexes.

    Suggestion: try reducing the number of the generated numbers (say 16 instead of 32768) and, after vector generation and multiset copy, print both of they.

    Something as follows

    #include <algorithm>
    #include <iostream>
    #include <vector>
    #include <set>
    
    
    int main ()
     {
       std::vector<unsigned> v(16);
       std::generate(v.begin(), v.end(), rand);
    
       std::multiset<unsigned> m(v.begin(), v.end());
    
       for ( auto const & ui : v )
          std::cout << ui << ' ';
    
       std::cout << std::endl;
    
       for ( auto const & ui : m )
          std::cout << ui << ' ';
    
       std::cout << std::endl;
     }
    

    Running it I get

    1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649 1189641421 1025202362 1350490027 783368690 1102520059 2044897763 1967513926 
    424238335 596516649 719885386 783368690 846930886 1025202362 1102520059 1189641421 1350490027 1649760492 1681692777 1714636915 1804289383 1957747793 1967513926 2044897763
    

    that seems to me absolutely reasonable.

    How do you copy the values in a std::vector into a std::multiset?

    As you've done is OK, as far I understand.