使用 C++ STL 打乱数组
在这里我们将看到 C++ 中的 shuffle 和 random_shuffle。这些函数用于打乱 C++ 中的数组元素。我们也可以使用向量而不是数组,用法类似。让我们先看看 random_shuffle()。它用于随机重新排列范围 [left, right) 内的元素。此函数随机交换每个元素与其一些随机选择的其他元素的位置。
我们可以提供一些随机生成器函数来指定每次选择哪个元素。如果我们不提供,它将使用它自己的随机生成器函数。
示例
#include <bits/stdc++.h>
using namespace std;
int myRandomGenerator(int j) {
return rand() % j;
}
main() {
srand(unsigned(time(0)));
vector<int> arr;
for (int j = 1; j < 20; ++j) //generate 20 numbers and add them into vector arr
arr.push_back(j);
random_shuffle(arr.begin(), arr.end()); //use inbuilt random function to shuffle
cout << "arr elements:";
for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
cout << ' ' << *i;
cout << endl;
// using myRandomGenerator
random_shuffle(arr.begin(), arr.end(), myRandomGenerator);
cout << "arr elements:";
for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
cout << ' ' << *i;
cout << endl;
}
输出
arr elements: 5 14 15 6 3 16 13 12 10 2 4 1 17 9 18 11 7 8 19 arr elements: 8 10 5 6 14 1 15 3 19 16 13 18 7 9 4 12 11 17 2
现在让我们看看 shuffle() 函数是什么。它也用于随机重新排列范围 [left, right) 内的元素。它需要一个均匀随机数生成器。
示例
#include <bits/stdc++.h>
using namespace std;
main() {
vector<int> arr;
unsigned seed = 0;
for (int j = 1; j < 20; ++j) //generate 20 numbers and add them into vector arr
arr.push_back(j);
shuffle(arr.begin(), arr.end(), default_random_engine(seed));
cout << "arr elements:";
for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
cout << ' ' << *i;
cout << endl;
}输出
arr elements: 19 7 5 6 12 4 13 3 1 17 11 14 18 2 8 15 9 10 16
random_shuffle() 和 shuffle() 之间的唯一区别在于,random_shuffle() 使用 rand() 函数生成随机索引,而 shuffle() 使用均匀随机数生成器。但是,如果我们使用均匀随机数生成器传递给 random_shuffle(),则它将生成某种结果。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP