首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::shuffle

Defined in header <algorithm>

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

(1)

(until C++17) (deprecated in C++14)

(2)

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

(until C++11)

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

(since C++11) (until C++17) (deprecated in C++14)

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

(3)

(since C++11)

重新排序给定范围内的元素[first, last)使得这些元素的每一个可能的排列都具有相同的出现概率。

1%29随机数生成器是实现定义的,但是函数std::rand经常被使用。

2%29随机数发生器是函数对象。r...

3%29随机数发生器是函数对象。g...

参数

first, last

-

the range of elements to shuffle randomly

r

-

function object returning a randomly chosen value of type convertible to std::iterator_traits<RandomIt>::difference_type in the interval [0,n) if invoked as r(n)

g

-

a UniformRandomBitGenerator whose result type is convertible to std::iterator_traits<RandomIt>::difference_type

类型要求

---。

-性病::清除[医]参照系[医]T型<URBG>必须满足UniformRandomBitGenerator的要求。

返回值

%280%29

复杂性

直线在之间的距离firstlast...

可能的实施

第一版

*。

模板<类随机>空随机[医]洗牌%28--第一次,最后一次--%29{TypeName STD::iterator[医]性状<RandomIt>*差异[医]类型i,n;n=最后一次;对于%28i=n-1;i>0;-i%29{使用std::交换;交换%281我,第一兰德%28%29%%28I+1%29%29;//rand%28%29%%28i+1%29实际上是正确的,因为所生成的数字//在大多数i值中没有均匀分布。正确的实现//将需要从本质上重新实现C++11 std::[医]INT[医]分布,//超出了本示例的范围。}}

第二版

模板<类随机,类随机>无效随机[医]洗牌%28--先随机,最后--随机--最后,--RandomFunc&r%29{type Name STD::iterator[医]性状<RandomIt>*差异[医]类型i,n;n=最后一次;对于%28i=n-1;i>0;-i%29{使用std::交换;交换%281我,第一R%28I+1%29%29;}

第三版

模板<class Randomit,类UniformRandomBitGenerator>voidShufferof28Randomit,Randomit Lest,UniformRandomBitGenerator&g%29{tyduf type Name std::iterator[医]性状<RandomIt>*差异[医]类型差异[医]T;tyUIDEf STD::Uniform[医]INT[医]分布<差[医]T>DIR[医]t;tyduif type Name disr[医]T::Param[医]Param型[医]t;disr[医]Dd;Dff[医]Tn=最后一位;对于%28diff[医]ti=n-1;i>0;-i%29{使用STD::SWAP;交换%28First我,第一D%28g,Param[医]t%280,i%29%29%29;}

下面的代码随机地对整数1.10进行洗牌:

二次

代码语言:javascript
复制
#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
 
int main()
{
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
    std::random_device rd;
    std::mt19937 g(rd());
 
    std::shuffle(v.begin(), v.end(), g);
 
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
}

二次

可能的产出:

二次

代码语言:javascript
复制
8 6 10 4 2 3 7 1 9 5

二次

另见

next_permutation

generates the next greater lexicographic permutation of a range of elements (function template)

prev_permutation

generates the next smaller lexicographic permutation of a range of elements (function template)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券