C++11 random numbers and std::bind interact in unexpected way

丶灬走出姿态 提交于 2019-12-03 13:53:55

When binding, a copy of rng_engine is made. If you want to pass a reference, this is what you have to do :

auto rng = std::bind(dist, std::ref(rng_engine));

The std::uniform_real_distribution::operator() takes a Generator & so you will have to bind using std::ref

#include <random>
#include <functional>

int main()
{
    std::mt19937 rng_engine;

    printf("With bind\n");
    for(int i = 0; i < 5; ++i) {
        std::uniform_real_distribution<double> dist(0.0, 1.0);
        auto rng = std::bind(dist, std::ref(rng_engine));
        printf("%g\n", rng());
    }

    printf("Without bind\n");
    for(int i = 0; i < 5; ++i) {
        std::uniform_real_distribution<double> dist(0.0, 1.0);
        printf("%g\n", dist(rng_engine));
    }
}

bind() is for repeated uses.

Putting it outside of the loop...

std::mt19937 rng_engine;
std::uniform_real_distribution<double> dist(0.0, 1.0);
auto rng = std::bind(dist, rng_engine);

for(int i = 0; i < 5; ++i) {
    printf("%g\n", rng());
}

... gives me the expected result:

0.135477
0.835009
0.968868
0.221034
0.308167
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!