生成随机数

打乱数组中的内容

参考1

参考2

目前我用到的是std::shuffle_order_engine.功能是打乱数组中的内容


random功能主要由两个部分组成:generators和distribution(不一定用分布)

  1. generators

    a.Pseudo-random(伪随机数) number engines (templates)

    b. Engine adaptors

    c. 伪随机数引擎(实例化)

    d.随机数生成器

    random_device

  2. distributions

    Uniform:

实例1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <algorithm>
#include <random>
#include <functional>
#include <chrono> // std::chrono::system_clock
//refernce:http://www.cplusplus.com/reference/random/

int main(_In_ int _Argc, _In_reads_(_Argc) _Pre_z_ char ** _Argv, _In_z_ char ** _Env)
{
//该seed使得每次运行的结果都不同
//用时间作为seed或者随机数生成器作为seed
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::uniform_int_distribution<int> distribution(1, 6);
// generates number in the range 1..6
for (size_t i = 0; i < 10; i++)
{
int dice_roll = distribution(generator);
std::cout << dice_roll << " ";
}
std::cout << std::endl;
//为了重复使用将两着绑定在一起
auto dice = std::bind(distribution, generator);

for (size_t i = 0; i < 10; i++)
{
int wisdom = dice() + dice() + dice();
std::cout << wisdom << " ";
}
getchar();
return 0;
}

输出:

3 1 3 6 5 2 6 6 1 2
9 8 11 13 9 12 12 9 5 9

实例2:(使用Engine adaptors:shuffle打乱vector顺序)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <vector>
#include <algorithm> // std::move_backward
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock

int main(int argc, char* argv[])
{
std::vector<int> v;

for (int i = 0; i < 10; ++i) {
v.push_back(i);
}

// obtain a time-based seed:
//unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
//std::shuffle(v.begin(), v.end(), std::default_random_engine(seed));
//或者用随机数生成器
std::random_device rand_dev;
std::shuffle(v.begin(), v.end(), std::default_random_engine(rand_dev()));

for (auto& it : v) {
std::cout << it << " ";
}

std::cout << "\n";
getchar();
return 0;
}

输出:

9 1 4 6 2 7 0 5 3 8

# C++, STL, std

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×