How to sample without replacement using c++ unifor

2019-02-28 14:26发布

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

标签: c++ random
1条回答
爷的心禁止访问
2楼-- · 2019-02-28 15:22

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.

Reference http://en.cppreference.com/w/cpp/algorithm/random_shuffle

查看更多
登录 后发表回答