Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

is stl::random_shuffle seedable?

Status
Not open for further replies.

wduty

Programmer
Jun 24, 2000
271
US
random_shuffle produces the same random order each time. Is there any way the seed std::random_shuffle? (srand didn't help).


#include <vector>
#include <algorithm>
#include <iostream.h>

typedef struct {int i;} TESTSTRUCT;
using namespace std;

int main()
{
vector<TESTSTRUCT> vec;
vector<TESTSTRUCT>::iterator it;

TESTSTRUCT t;

for (int n=0; n<10; n++)
{
t.i = n;
vec.push_back(t);
}

std::random_shuffle(vec.begin(), vec.end());

it = vec.begin();
while(it != vec.end())
{
cout << it->i << endl;
it++;
}
return 0;
}


I always get
6
8
9
2
1
4
3
7
0
5
 
std::random_shuffle uses one of two internal random number generators. The first is plain old rand(). The other is lrand48(). I am not sure where lrand48 is defined, but it seems to not use it on my system. Since it uses rand(), srand(time(0)) at the beginning of the main should make it work OK. However, if STL wants to use the lrand48(), then you would need to seed that function, which I do not know how to do.

A possibility (that I cannot test since srand(time(0)) works for me) is to use a #define to tell STL to use rand() and not lrand48(). This is can be done by adding:

#ifndef __STL_NO_DRAND48
#define __STL_NO_DRAND48
#endif

This will tell STL to not use lrand48() and instead use rand().

Hope this helps...
-Al
 
Well the define trick didn't work but it looks like it should because other sites around the net say to do the same thing. However, I did get it to work. The test program I posted above was being compiled with borland 5.5. When I compiled it with VC++ it worked.

Thanks for your help though.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top