C++ 高效随机排列数组元素 (Fisher-Yates 算法)
可以使用 Fisher-Yates 算法来随机排列数组元素。该算法的时间复杂度是 O(n),效率较高。下面是使用 C++ 实现的代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
using namespace std;
void randomizeArray(vector<int>& nums) {
random_device rd;
mt19937 gen(rd());
shuffle(nums.begin(), nums.end(), gen);
}
int main() {
vector<int> nums = {0, 1, 2};
randomizeArray(nums);
for (int num : nums) {
cout << num << ' ';
}
cout << endl;
return 0;
}
这段代码使用了 C++ 的 random_device 和 mt19937 来生成随机数种子,然后使用 shuffle 函数来随机排列数组元素。运行结果类似于以下输出:
1 0 2
每次运行结果都会不同,因为数组元素的顺序是随机排列的。
原文地址: http://www.cveoy.top/t/topic/lMBD 著作权归作者所有。请勿转载和采集!