c++ - C++ 中使用 <random> 的随机数顺序

标签 c++ c++11 random operator-precedence

我有以下代码,我编写这些代码是为了测试一个更大程序的一部分:

#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/

相关文章:

python - 使用 numpy.random.normal 时如何指定上限和下限

c++ - "template<class C> void mini(C &a4, C b4) { a4 = min(a4, b4); }"定义是什么意思?

c++ - 如何调试occi使用Clion?

c++ - 在默认构造函数中声明 arr 时未在此范围内声明“arr”

c++ - 比较两个std::chrono::time_point实例时出错

javascript - 使用 Javascript 的真实或更好的随机数

c++ - 我收到错误 : "in function main: undefined reference to Fraction::Fraction()"

c++ - 从文件中获取字符而不是 getchar

c++ - 为什么 move ctor 比 copy ctor 慢?

Java:变量已在方法中定义