vendredi 10 mai 2019

std::shuffle with a lambda

std::random_shuffle which is removed from C++17 onwards allowed passing in a functor/lambda with ease which would generate a customizable random output based on the input n. How can the same be achieved with std::shuffle.

A functor for example Im originally using is(can also be expressed as a lambda):

template <typename GENERATOR>
struct Rng
{
    Rng(GENERATOR& generator) : m_generator(generator){};

    // Return an integer in the range [0, n), with uniform probability.
    uint32_t operator()(uint32_t n)
    {
        std::uniform_int_distribution<uint32_t> dist(0, n - 1);
        return dist(m_generator);
    }

private:
    GENERATOR& m_generator;
};

This question(Using std::shuffle with custom rng?) provides some specifications for a stricter Rng class specification instead. Is it not possible to customize instead with a lambda?




Aucun commentaire:

Enregistrer un commentaire