使用boost :: random作为std :: random_shuffle的RNG [英] Using boost::random as the RNG for std::random_shuffle

查看:197
本文介绍了使用boost :: random作为std :: random_shuffle的RNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,使用mt19937随机数字生成器从boost :: random。我需要做一个random_shuffle,并希望为此生成的随机数来自这种共享状态,以便它们可以是确定性的相对于mersenne twister先前生成的数字。

I have a program that uses the mt19937 random number generator from boost::random. I need to do a random_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.

我试过这样:

void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
    struct bar {
        boost::mt19937 &_state;
        unsigned operator()(unsigned i) {
            boost::uniform_int<> rng(0, i - 1);
            return rng(_state);
        }
        bar(boost::mt19937 &state) : _state(state) {}
    } rand(state);

    std::random_shuffle(vec.begin(), vec.end(), rand);
}

但是我得到一个模板错误用rand调用random_shuffle。但是,它的工作原理是:

But i get a template error calling random_shuffle with rand. However this works:

unsigned bar(unsigned i)
{
    boost::mt19937 no_state;
    boost::uniform_int<> rng(0, i - 1);
    return rng(no_state);
}
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
    std::random_shuffle(vec.begin(), vec.end(), bar);
}

可能是因为它是一个实际的函数调用。但显然这不保持状态从原来的梅森捻线机。是什么赋予了?有没有办法做我想做没有全局变量的尝试?

Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables?

推荐答案

在C ++ 03,基于函数局部类型实例化模板。如果你移动rand类的函数,它应该工作正常(免责声明:未经测试,可能有其他阴险的错误)。

In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs).

这个要求已放宽C ++ 0x,但我不知道是否已经在GCC的C ++ 0x模式中实现了更改,我会惊讶地发现它存在于任何其他编译器。

This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler.

这篇关于使用boost :: random作为std :: random_shuffle的RNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆