Is there some function, similar to srand()
, that I need to call to make sure that std::random_shuffle()
always produces different results? i.e. if I call it several times with the same data, I want the order to be different every time. How can I make sure of that?

- 88,262
- 77
- 290
- 428
-
3That doesn't sound very random to me... – Blindy Aug 03 '11 at 19:15
-
1@Blindy: It's random, but the results are not uniformly distributed. – John Bartholomew Aug 03 '11 at 19:18
-
srand is quite good. If it is not good enough for your need, search for other random generators (maybe boost) – BЈовић Aug 03 '11 at 19:18
-
3Make sure you **NEVER** call srand() more than once in a program. – Martin York Aug 03 '11 at 19:23
-
`srand()` doesn't make sure anything produces different results. @John: it's less and less random each time, because it's more and more predictable each time. – R. Martinho Fernandes Aug 03 '11 at 19:47
-
@LokiAstari there are plenty of reasons to. If you care about running a MC algorithm multiple times with different parameters but the same random number stream, for example. – geometrian Nov 03 '14 at 05:32
6 Answers
std::random_shuffle
has two forms. One that takes 2 arguments (begin/end iterators), and one that takes 3 (begin/end iterator and a random generator).
The first form uses std::rand()
, so you would use std::srand()
to seed it's random number generator. You can also use the 3-argument version and provide the RNG yourself.

- 20,507
- 3
- 48
- 68
-
7As I understand it, how the first form implements it is its business. Some platforms may not use `std::rand`. – Tom Kerr Aug 03 '11 at 19:26
-
You're right. I was looking at the libstdc++ version. The original author should consult the documentation for your STL. Or if they don't want to rely on that, they should use the 3rd form and use something like `boost::random` or the C++0x `std::random`. – Dave S Aug 03 '11 at 19:30
random_shuffle is deprecated since C++14 (removed in C++17) and replaced with shuffle (exists since C++11) http://en.cppreference.com/w/cpp/algorithm/random_shuffle
possible usage:
shuffle(items.begin(), items.end(), std::default_random_engine(std::random_device()()));

- 524
- 5
- 15
Generally call srand(time(NULL))
before calling std::random_shuffle()
would give you what you need, it give you different result each time you call std::random_shuffle()
. It's because std::random_shuffle()
internally calls rand()
in many popular implementations (e.g. VS-2008 and GCC).
Of course you can supple a RNG yourself if you want to call the other overloaded std::random_shuffle
with a extra parameter.

- 49,934
- 160
- 51
- 83

- 5,819
- 7
- 49
- 75
As a last resort, you can:
- Call
std::random_shuffle
- Compute a hash of the sequence, store it in a
std::set
- Discard if the hash is already present
I fail to see how using a custom generator could guarantee that the sequence is unique.

- 55,948
- 11
- 128
- 197