C++ 使用 std 库高效随机排列 0、1、2 三元素数组
以下是一种使用 std 库方法,通过随机生成索引来交换数组元素,实现随机排列功能。
#include <iostream>
#include <algorithm>
#include <vector>
#include <random>
int main() {
std::vector<int> arr{0, 1, 2};
std::random_device rd;
std::mt19937 gen(rd());
for (int i = 0; i < arr.size(); i++) {
std::uniform_int_distribution<> dis(i, arr.size() - 1);
int randIndex = dis(gen);
std::swap(arr[i], arr[randIndex]);
}
for (int num : arr) {
std::cout << num << " ";
}
return 0;
}
这段代码使用了 C++11 中的 std::random_device 和 std::mt19937 来生成随机数引擎,然后使用 std::uniform_int_distribution 来生成指定范围内的随机索引值。通过不断交换当前位置的元素和随机位置的元素,最终实现了数组的随机排列。
原文地址: http://www.cveoy.top/t/topic/lMB8 著作权归作者所有。请勿转载和采集!