提前感谢您的阅读.我是C++的新手(虽然不是一般的编程)并且不太了解.我正在处理的问题需要大量高质量的随机数,默认的rand()函数是不够的.我尝试使用"随机"库但无法使其工作.以下简单代码:
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <random>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
mt19937 gen(random_device());
normal_distribution<double> randn(0.0, 1.0);
double t;
for (int i = 0; i < 50; i++){
t = randn(gen); //program compiles correctly if call to randn is omitted
cout << t << "\n";
}
int a;
cin >> a;
}
Run Code Online (Sandbox Code Playgroud)
无法编译,给我10个错误,大多数都是这样的:
error C2780: '_Rty std::_Nrand(_Engine &,float,_Rty)' : expects 3 arguments - 2 provided
Run Code Online (Sandbox Code Playgroud)
我尝试了其他发电机和概率分布 - 同样的问题.有任何想法吗?
mt19937 gen(random_device());
Run Code Online (Sandbox Code Playgroud)
这是所谓最令人烦恼的解析的一个例子.编译器实际上将其解析为一个函数的声明,该函数调用gen一个类型的参数random_device()(即函数采用零参数并返回std::random_device)并返回std::mt19937.首先,您必须将其更改为:
mt19937 gen(random_device{}); // new C++11 uniform initialization syntax
Run Code Online (Sandbox Code Playgroud)
但这仍然是错误的,因为构造函数的参数std::mt19937应该是种子值.random_device{}是一个在调用它时产生种子值的对象operator().所以实际的正确声明是:
mt19937 gen(random_device{}());
Run Code Online (Sandbox Code Playgroud)