将向量的内容复制到多重集中

Copy contents of a vector into a multiset

我试过像这样将 std::vector 的内容复制到 std::multiset 中:

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

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

但是,这只会复制索引 0-32768 而不是值

如何将 std::vector 中的值复制到 std::multiset 中?

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

你确定吗?

从您报告的屏幕截图来看,在我看来您有

0 1 3 4 6 6 6 ...

想一想你在 std::multiset 中复制 std::vector 得到的结果:你得到相同的数字重新排序。

所以生成32768个随机数,你得到了一个0,一个1,没有2,一个3,一个4,三个或更多6。

向量中的位置确实不同;在多集中,它们位于开头,因此您可以认为您已经复制了索引。

建议:尝试减少生成数字的数量(例如 16 而不是 32768),然后在矢量生成和多集复制之后,将它们都打印出来。

内容如下

#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;
 }

运行 我明白了

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

在我看来这绝对合理。

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

据我所知,你做的还可以。