每次调用函数时随机数都相同

Voi*_*ips 3 c++ random c++11

每次我运行程序时,这些数字都是随机的,但在同一次运行中它们保持不变。我希望每次调用函数时数字都是随机的。我确实在 main() 中播种了生成器。

    std::random_device device;
    std::mt19937 generator(device());
Run Code Online (Sandbox Code Playgroud)

我的功能

void takeAssignment(std::vector<Student> &students,
                    const int min, const int max,
                    std::mt19937 e)
{
    std::uniform_int_distribution<int> dist(min, max);
    // all students take the assignment
    for (auto &s : students)
    {
        // random performance
        int score{dist(e)};
        s.addScore(score, max);
        std::cout << s.getName() << "'s score: " << score << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,每次在 min 为 0 和 max 为 10 的情况下调用该函数时,都会打印该函数的输出

Abril Soto's score: 1
Bailey Case's score: 9
Run Code Online (Sandbox Code Playgroud)

在那次运行期间。

将 dist 放入循环也不起作用,数字保持不变。

E.N*_*N.D 7

您通过按值调用传递生成器,从而创建一个没有种子的副本并生成相同的值。尝试在函数参数中通过引用传递:像

std::mt19937& e