我有以下代码,我编写这些代码是为了测试一个更大程序的一部分:
#include <fstream>
#include <random>
#include <iostream>
using namespace std ;
int main()
{
mt19937_64 Generator(12187) ;
mt19937_64 Generator2(12187) ;
uniform_int_distribution<int> D1(1,6) ;
cout << D1(Generator) << " " ;
cout << D1(Generator) << " " << D1(Generator) << endl ;
cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;
ofstream g1("g1.dat") ;
g1 << Generator ;
g1.close() ;
ofstream g2("g2.dat") ;
g2 << Generator2 ;
g2.close() ;
}
两个生成器的种子值相同,因此我希望输出中的第二行与第一行相同。相反,输出是
1 1 3
1 3 1
*.dat
文件中打印的两个生成器的状态是相同的。我想知道在随机数生成中是否可能存在一些隐藏的多线程导致顺序不匹配。
我在 Linux 上使用 g++
版本 5.3.0 编译,带有 -std=c++11
标志。
提前感谢您的帮助。
最佳答案
x << y
是对 operator<<(x, y)
的函数调用的语法糖.
您会记得,c++ 标准对函数调用的参数的求值顺序没有任何限制。
因此编译器可以自由地发出先计算 x 或先计算 y 的代码。
来自标准:§5 注 2:
Operators can be overloaded, that is, given meaning when applied to expressions of class type (Clause 9) or enumeration type (7.2). Uses of overloaded operators are transformed into function calls as described in 13.5. Overloaded operators obey the rules for syntax specified in Clause 5, but the requirements of operand type, value category, and evaluation order are replaced by the rules for function call.
关于c++ - C++ 中使用 <random> 的随机数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35060111/