random_shuffle question

Hi there, I'm looking to have the list of words in the vector shuffled randomly each time at the start of the program. However, they shuffle in the same order every time even thought it seems to be seeded correctly. Any advice would be greatly appreciated.
Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>

using namespace std;

int main()

{
    vector<string> words;
    words.push_back("phlegm");
    words.push_back("analyze");
    words.push_back("calculator");
    words.push_back("trumpet");
    words.push_back("speaker");
    words.push_back("throne");
    
    vector<string>::const_iterator iter;
    
    srand(static_cast<unsigned int>(time(0)));
    random_shuffle(words.begin(), words.end());
    for(iter = words.begin(); iter != words.end(); ++iter)
    {
        cout << *iter;
    }
    
    return 0;
}
Did you wait at least one second before you ran your program again?
Yes, I've waited eons.
Strange, when I run your program I get different outputs. What compiler do you use?
Most curious indeed. I'm running xcode.
The standard doesn't specify what random generator random_shuffle uses so it doesn't have to use rand() even though it does on most implementations. If you want you could pass a random generator function to random_shuffle as a third argument.

1
2
3
4
5
6
7
8
int random_shuffle_rand(int n)
{
	return rand() % n;
}

...

	random_shuffle(words.begin(), words.end(), random_shuffle_rand);
Last edited on
could also use shuffle() if you prefer the random number generators from <random> (I do)
I got it to work using shuffle(). However, it's using some syntax that I'm not at all familiar with.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
#include <array>
#include <random>
#include <chrono>

using namespace std;

int main()

{
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    
    vector<string> words;
    words.push_back("phlegm");
    words.push_back("analyze");
    words.push_back("calculator");
    words.push_back("trumpet");
    words.push_back("speaker");
    words.push_back("throne");
    
    vector<string>::const_iterator iter;
    
    shuffle(words.begin(), words.end(), std::default_random_engine(seed));
    for(iter = words.begin(); iter != words.end(); ++iter)
    {
        cout << *iter;
        cout << "\n";
    }
    
    return 0;
}


I still find it odd that random_shuffle didn't work well for me. Thanks for all the help!
Topic archived. No new replies allowed.