views:

110

answers:

1

I learned to program in C# and have started to learn C++. I'm using the Visual Studio 2010 IDE. I am trying to generate random numbers with the distribution classes available in <random>. For example I tried doing the following:

    #include <random>
std::normal_distribution<double> *normal = new normal_distribution<double>(0.0, 0.0);
std::knuth_b *engine = new knuth_b();
std::variate_generator<knuth_b, normal_distribution<double>> *rnd;  
rnd = new variate_generator<knuth_b, normal_distribution<double>>(engine, normal);

The last line gives a compiler error: IntelliSense: no instance of constructor "std::tr1::variate_generator<_Engine, _Distrib>::variate_generator [with _Engine=std::tr1::knuth_b, _Distrib=std::tr1::normal_distribution]" matches the argument list

My arguments look ok to me, what am I doing wrong? When the variate_generator class here is instantiated, which method do you call to get the next random number i.e. .NET's System.Random.Next()?

+3  A: 

There is no variate_generator in C++0x, but std::bind works just as well. The following compiles and runs in GCC 4.5.2 and MSVC 2010 Express:

#include <random>
#include <functional>
#include <iostream>
int main()
{
    std::normal_distribution<> normal(10.0, 3.0); // mean 10, sigma 3
    std::random_device rd;
    std::mt19937 engine(rd()); // knuth_b fails in MSVC2010, but compiles in GCC
    std::function<double()> rnd = std::bind(normal, engine);

    std::cout << rnd() << '\n';
    std::cout << rnd() << '\n';
    std::cout << rnd() << '\n';
    std::cout << rnd() << '\n';
}

PS: avoid new when you can.

Cubbi
Cool thanks it works and now I know about the <functional> library.
T. Webster