可以使用 std::shuffle 函数来随机排列数组的位置。以下是一个使用 std::shuffle 函数随机排列数组的示例代码:

#include <iostream>
#include <random>
#include <algorithm>
#include <vector>
#include <iterator>

int main() {
    std::vector<int> arr = {0, 1, 2};

    // 使用默认随机数引擎
    std::random_device rd;
    std::mt19937 g(rd());

    // 随机排列数组
    std::shuffle(arr.begin(), arr.end(), g);

    // 输出随机排列后的数组
    std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(std::cout, ' '));
    std::cout << std::endl;

    return 0;
}

运行示例代码的结果可能为:2 0 1 或 1 0 2 或 0 2 1 等等,表示随机排列后的数组。

C++ 使用 std::shuffle 随机排列数组元素 (0, 1, 2)

原文地址: https://www.cveoy.top/t/topic/lMEK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录