如何使用C ++ Uniform_int_distribution进行采样而不进行替换 [英] How to sample without replacement using c++ uniform_int_distribution

查看:218
本文介绍了如何使用C ++ Uniform_int_distribution进行采样而不进行替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在c ++随机库中使用uniform_int_distribution.但是,仅在替换时进行采样,如下例所示.如何在不更换的情况下取样?

I want to use the uniform_int_distribution in the c++ random library. However, it only does the sampling with replacement, as in the example below. How can I sample without replacement?

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

推荐答案

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

Use std::shuffle on, say, a std::array<int> or a std::vector<int>, initialised to {1, 2, 3, 4}.

然后依次读取容器中的内容.

Then read back the container contents in order.

与绘制随机数并仅在以前没有绘制它时才接受它相比,它具有更好的统计属性.

This will have better statistical properties than drawing a random number and accepting it only if it hasn't been drawn before.

参考 http://en.cppreference.com/w/cpp/algorithm/random_shuffle

这篇关于如何使用C ++ Uniform_int_distribution进行采样而不进行替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆