c++ - 如何使用 C++ uniform_int_distribution 进行无替换采样

标签 c++ random

<分区>

我想使用 c++ 随机库中的 uniform_int_distribution。但是,它只进行有放回的采样,如下例所示。如何在不更换的情况下进行采样?

#include <iostream>
#include <random>

int main()
{
  std::default_random_engine generator;
  std::uniform_int_distribution<int> distribution(1,4);

  for(int i=0; i<4; ++i)
    std::cout << distribution(generator) << std::endl;

  return 0;
}

最佳答案

使用 std::shuffle在,比方说,std::array<int>std::vector<int> , 初始化为 {1, 2, 3, 4} .

然后按顺序读回容器内容。

这将比抽取一个随机数并仅在之前未抽取过的情况下才接受它具有更好的统计特性。

引用 http://en.cppreference.com/w/cpp/algorithm/random_shuffle

关于c++ - 如何使用 C++ uniform_int_distribution 进行无替换采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802205/

相关文章:

c++ - Delphi 中的类型转换指针添加

c++ - std::stoi 在 MinGW 上的 g++ 4.6.1 中不存在

php - 不确定如何随机化这个

c - 函数 srand、rand 和 system 的隐式声明

c++ - 防止 ZMQ c++ 调用 rand()

c++ - 如何在我的函数中返回一个二维数组?

c++ - 如何在 ubuntu 中为 c++ 配置 Visual Studio 代码

c++ - 无法推断模板参数 - 泛型函数

c - 随机数(加法游戏)问题

c - 这段代码在哪里生成随机数?