Reputation: 1090
#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?
Upvotes: 2
Views: 493
Reputation: 172894
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);
Upvotes: 2
Reputation: 409166
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).
Upvotes: 2