Search code examples
c++boostboost-random

random_shuffle error : inability to pass a minstd_rand generator


Following the documentation provided here I am trying to randomly permute a std::vector like this:

#include <vector>
#include <boost/random/linear_congruential.hpp>
#include <boost/range/algorithm.hpp>

int main(){
    std::vector<int> vecint;
    for(int i = 0; i < 10; i++)
        vecint.push_back(i);
    boost::minstd_rand gen(0);
    boost::range::random_shuffle(vecint, gen);
}

This however does not compile. Godbolt link is here: https://godbolt.org/z/zjhh6r3xd

I think that the following condition specified in the documentation does not hold:

RandomAccessRange's distance type is convertible to Generator's argument type.

How can I find out the distance type of std::vector and the particular generator's argument type to figure out if they are compatible or not?


Solution

  • That minstd_rand is not generator functor but engine. Something like that works:

    #include <iostream>
    #include <vector>
    #include <boost/random/linear_congruential.hpp>
    #include <boost/random/uniform_int.hpp>
    #include <boost/random/variate_generator.hpp>
    #include <boost/range/algorithm.hpp>
    
    int main() {
        std::vector<int> vecint;
        for(int i = 0; i < 10; i++)
            vecint.push_back(i);
        boost::minstd_rand engine(0);
        boost::uniform_int<> distribution;
        boost::variate_generator gen(engine, distribution);
        boost::range::random_shuffle(vecint, gen);
        boost::range::copy(vecint, std::ostream_iterator<int>(std::cout, " "));
        std::cout << std::endl;
    }