gpt4 book ai didi

c++ - 实现之间的随机输出不同

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:13 25 4
gpt4 key购买 nike

我用 libstdc++、libc++ 和 dinkumware 试过这个程序:

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

int main()
{
std::vector<int> v(10);

std::mt19937 rand{0};
std::uniform_int_distribution<> dist(
1, 10
);

std::generate_n(v.begin(), v.size(),
std::bind(dist, rand));

for (auto i : v)
std::cout << i << " ";
}

输出分别是:

6 6 8 9 7 9 6 9 5 7 

6 1 4 4 8 10 4 6 3 5

5 10 4 1 4 10 8 4 8 4

每次运行的输出都是一致的,但如您所见,它们是不同的。解释一下?

最佳答案

uniform_int_distribution<> 不需要实现. [rand.dist.general] 指定:

The algorithms for producing each of the specified distributions are implementation-defined.

所有 [rand.dist.uni.int] 声明的是:

A uniform_int_distribution random number distribution produces random integers i, a <= i <= b, distributed according to the constant discrete probability function P(i | a, b) = 1/(b − a + 1) .

每个实现都可以按照自己的意愿自由实现这种分布。您看到的显然是三种不同的实现。

关于c++ - 实现之间的随机输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32746092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com