shuffle()函数介绍
C++中的shuffle()函数用于将一个序列中的元素随机打乱,其原型如下:
template< class RandomIt, class URBG >
void shuffle( RandomIt first, RandomIt last, URBG&& g );
其中,first
和last
表示要打乱的序列的起始和结束迭代器,g表示
随机性来源对象(比如均匀随机生成器)。
std::random_shuffle, std::shuffle - cppreference.com
shuffle函数使用场景
在游戏中,可以使用shuffle()函数将角色、道具等随机出现的位置进行打乱,增加游戏的趣味性
例子:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <random>
using namespace std;
int main()
{
vector<int> nums = { 1, 2, 3, 4, 5 };
shuffle(nums.begin(), nums.end(), default_random_engine(time(NULL))); // 将nums中的元素随机打乱
for (int num : nums)
{
cout << num << " ";
}
cout << endl;
return 0;
}
在密码学中,可以使用shuffle()函数对密钥进行随机打乱,以增加加密和解密的难度
例子:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <random>
using namespace std;
int main()
{
vector<char> key = { 'K', 'E', 'Y', 'S', 'O', 'V', 'E', 'R', 'N', 'D' };
shuffle(key.begin(), key.end(), default_random_engine(time(NULL))); // 将key中的元素随机打乱
for (char c : key)
{
cout << c << " ";
}
cout << endl;
return 0;
}
在统计学中,可以使用shuffle()函数对样本数据进行随机打乱,以便进行抽样调查等
例子:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <random>
using namespace std;
int main()
{
vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
mt19937 engine(time(NULL)); // 设置随机数引擎
shuffle(data.begin(), data.end(), engine); // 使用随机数引擎对data中的元素进行随机打乱
for (int num : data)
{
cout << num << " ";
}
cout << endl;
return 0;
}
总结
shuffle()函数是C++中用于将一个序列中的元素随机打乱的标准库函数,可以用于各种场景,如游戏开发、密码学、统计学等。在使用shuffle()函数时,需要注意设置随机数种子,以保证每次运行程序时都能得到不同的随机数序列。