随机 C++ 的多个种子

问题描述 投票:0回答:1

有没有办法传递多个数字(在我的例子中是 3)作为随机处理的种子?我需要结果是线性分布的伪随机值,所以我不能只使用

srand(x + y + z);
,因为
srand((x+n) + y + z);
会给出与
srand(x + (y+n) + z);
相同的结果,这是可预测的。

c++ random random-seed
1个回答
0
投票

在 C++ 中,您可以使用该库使用多个种子生成随机数。该库提供了各种引擎、发行版和实用程序,用于以灵活高效的方式生成随机数。

要使用多个种子生成随机数,可以使用

std::seed_seq
类来初始化随机数引擎,例如
std::mt19937
,这是一种广泛使用的伪随机数生成器引擎。以下是如何通过
std::seed_seq
使用多个种子的示例:

#include <iostream>
#include <random>

int main() {
    // Define your seeds
    unsigned int seed1 = 123;
    unsigned int seed2 = 456;
    unsigned int seed3 = 789;

    // Create a seed sequence with the provided seeds
    std::seed_seq seed_sequence{seed1, seed2, seed3};

    // Create a random engine and seed it with the seed sequence
    std::mt19937 engine(seed_sequence);

    // Generate random numbers using the engine
    std::uniform_int_distribution<int> distribution(1, 100); // Example distribution
    for (int i = 0; i < 10; ++i) {
        std::cout << distribution(engine) << std::endl;
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.