shuffle 洗牌算法

重排序给定范围 [first, last] 中的元素,使得这些元素的每个排列拥有相等的出现概率。

shuffle

shuffle 原型

template< class RandomIt, class URBG >
void shuffle( RandomIt first, RandomIt last, URBG&& g );

shuffle 使用

#include <random>   // random_device, mt19937
#include <algorithm>    // shuffle

std::shuffle(ps.begin(), ps.end(), std::random_device());

std::random_device rd;
std::mt19937 g(rd());
std::shuffle(v.begin(), v.end(), g);

random_shuffle

C++14 中弃用,C++17 中移除

random_shuffle 原型

template< class RandomIt >
void random_shuffle( RandomIt first, RandomIt last );

template< class RandomIt, class RandomFunc >
void random_shuffle( RandomIt first, RandomIt last, RandomFunc&& r );

random_shuffle 使用

std::random_shuffle(ps.begin(), ps.end());
std::random_shuffle(v.begin(), v.end(), std::mt19937());

愿此行,终抵群星!