简体   繁体   中英

std::random_shuffle not being seeded

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>


int main() {
    std::vector<short> a(256);
    for (short x = 0; x != 256; ++x) {
        a[x] = x;
    }
    for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl;
    std::cout << std::endl;

    std::srand(11);

    std::random_shuffle(a.begin(), a.end());
    for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl;
    std::cout << std::endl;

    for (short x = 0; x != 256; ++x) {
        a[x] = x;
    }
    for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl;
    std::cout << std::endl;

    std::srand(11);

    std::random_shuffle(a.begin(), a.end());
    for (auto x : a) { std::cout << x << ' '; } std::cout << std::endl;
}

So, here is my code. What I expect is, obviously, the same shuffle both times. What I get is, while the shuffles are consistent between launches, they are different and seem to ignore srand! What am I doing wrong here?

First note that the version of std::random_shuffle you use has been deprecated.

Also note (from the previous reference link)

...the function std::rand is often used.

The keyword here being often and not always .

If you want to make sure the same sequence is always created, then you should use one of the alternatives, passing either a specific random-number function, or use the std::shuffle function passing a generator (from the C++11 "new" PRNG classes ).

Note that for std::random_shuffle what random number generator is used is implementation-defined, it's not guaranteed to use std::rand .

You could use std::shuffle instead and pass it a random number generator:

std::random_device rd;
std::mt19937 g(rd());
std::shuffle(a.begin(), a.end(), g);

LIVE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM