且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从一组唯一值中选择唯一随机子集

更新时间:2023-02-05 16:52:39

创建随机排列 ,并选择 0,1,...,N-1 的第一个 M

Create a random permutation of the range 0, 1, ..., N - 1 and pick the first M of them; use those as indices into your original vector.

使用 std可以很容易地使用标准库进行随机排列:: iota 以及 std :: random_shuffle

std::vector<Heavy> v; // given

std::vector<unsigned int> indices(V.size());
std::iota(indices.begin(), indices.end(), 0);
std::random_shuffle(indices.begin(), indices.end());

// use V[indices[0]], V[indices[1]], ..., V[indices[M-1]]

您可以提供 random_shuffle 与您选择的随机数生成器;检查文件­男子&害羞的细节。

You can supply random_shuffle with a random number generator of your choice; check the docu­men­tation for details.