How to sample without replacement using c++ unifor

2019-02-28 15:17发布

问题:

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:

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



标签: c++ random