以下是一个使用 C++ 随机排列 0、1、2 三个元素位置的示例代码:

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

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

    // 使用随机数引擎和洗牌算法随机排列数组元素位置
    std::random_device rd;
    std::mt19937 rng(rd());
    std::shuffle(arr.begin(), arr.end(), rng);

    // 输出随机排列后的数组
    for (int i : arr) {
        std::cout << i << ' ';  // 将双引号改为单引号
    }
    std::cout << std::endl;

    return 0;
}

此代码使用了 C++ 标准库中的 random_device 来获取真正的随机数种子,然后使用 mt19937 随机数引擎和 shuffle 算法进行随机排列,最后通过循环输出随机排列后的数组。

C++ 随机排列 0, 1, 2 三个元素

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

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