您当前的位置: 首页 >  算法

鱼儿-1226

暂无认证

  • 0浏览

    0关注

    1100博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++ – 随机洗牌算法,std::random_shuffle和std::shuffle

鱼儿-1226 发布时间:2022-10-13 15:51:28 ,浏览量:0

1 std::random_shuffle和std::shuffle

std::random_shufflestd::shuffle处于头文件#include中。

std::random_shufflestd::shuffle都用于对给定容器范围内的元素重新进行洗牌,打乱顺序重新排序。不过由于std::random_shuffle在迭代器版本(不指定随机函数的情况下)通常依赖std::srand,并且依赖于全局状态,这导致元素洗牌后的不会很理想,所以std::random_shuffle在C++14中已经被弃用,在C++17中被剔除。我们可以使用std::shuffle替代std::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 );

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

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

C++

Copy

参数含义

  • first : 随机洗牌元素范围第一个元素
  • lats:随机洗牌元素范围最后一个元素
  • r:返回一个随机选择的可转换类型的值的函数对象
  • g:结果类型可转换为UniformRandomBitGenerator的参数
1.1 std::random_shuffle的使用 1.1.1 默认迭代器版本
#include 
#include 
#include 
#include 

template 
void PrintVector(const std::vector& vector)
{
    for_each(vector.begin(), vector.end(), [](T x) {
        std::cout             
关注
打赏
1604459285
查看更多评论
0.0397s