Not able to std::shuffle?

1

Code is basic:

#include <iostream>
#include <vector>
#include <random>
#include <chrono>
#include <algorithm>

int main(int argc, const char *argv[]) {
    std::vector<int> mSet = { 1, 2, 3, 4 };

    auto timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::seed_seq ss{ uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed >> 32) };
    std::mt19937_64 rng;
    std::shuffle(mSet.begin(), mSet.end(), rng);

    for (size_t i = 0; i < mSet.size(); i++) {
        std::cout << mSet[i] << " ";
    }
}

It always show to me the same sequence. Where am I wrong?

c++
random
stdvector
asked on Stack Overflow Nov 5, 2018 by markzzz

1 Answer

7

When you instantiated rng, you did not use ss. As such your seed is not used and the sequence will always be the same.

Looks like you meant:

std::mt19937_64 rng{ss};

Your compiler should be warning you that ss is unused. Do you have warnings turned off for some reason? Unfortunately GCC does not seem to warn about this even with -Wextra.


User contributions licensed under CC BY-SA 3.0