为什么样本不随机填充我的矢量?

Jon*_*Mee 4 c++ random algorithm dictionary vector

我正在尝试玩具sample程序:

map<int, char> foo { { 1, 'a' }, { 2, 'b' }, { 3, 'c' } };
vector<pair<decltype(foo)::key_type, decltype(foo)::mapped_type>> bar(size(foo));

sample(begin(foo), end(foo), begin(bar), size(foo), mt19937{ random_device{}() });
Run Code Online (Sandbox Code Playgroud)

Live Example

但bar始终包含foo有序的内容.这是一个gcc实现问题,还是我一再不幸?

for*_*818 5

std::sample从您传递的范围中选择元素.来自cppreference(强调我的):

选择序列中的n个元素[first; 最后)使每个可能的样本具有相同的出现概率,并将那些选定的元素写入输出迭代器中.使用随机数生成器g生成随机数.

如果n大于序列中元素的数量,则选择last-first元素.

我认为文档可以更清楚,但仅last-first在请求元素的数量更大的情况下返回,只有在每个元素最多选择一次时才有意义.

尝试:

map<int, char> foo { { 1, 'a' }, { 2, 'b' }, { 3, 'c' } };
vector<pair<decltype(foo)::key_type, decltype(foo)::mapped_type>> bar(size(foo)-1);

sample(begin(foo), end(foo), begin(bar), bar.size(), mt19937{ random_device{}() });
Run Code Online (Sandbox Code Playgroud)

得到两个随机样本foo.

另请注意

仅当PopulationIterator满足ForwardIterator的要求时,该算法才是稳定的

也就是说,你总是得到相同的结果并不是运气不好.