C++ randomly sample k numbers from range 0:n-1 (n > k) without replacement

后端 未结 5 1432
死守一世寂寞
死守一世寂寞 2021-01-02 13:11

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

5条回答
  •  Happy的楠姐
    2021-01-02 13:34

    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
    

提交回复
热议问题