I\'m working on porting a MATLAB simulation into C++. To do this, I am trying to replicate MATLAB\'s randsample() function. I haven\'t figured out an efficient way to do thi
Starting from C++17, there's a standard function for that: std::sample in library. It is guaranteed to have linear time complexity.
Sample (pun intended) usage:
#include
#include
#include
#include
#include
int main()
{
std::vector population {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector sample;
std::sample(population.begin(), population.end(),
std::back_inserter(sample),
5,
std::mt19937{std::random_device{}()});
for(int i: sample)
std::cout << i << " "; //prints 5 randomly chosen values from population vector