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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

random_shuffle() problem

Status
Not open for further replies.

GMX

Programmer
Mar 21, 2003
33
US
Here's a function from my prog:

void CDeck::Deal(void)
{
srand((unsigned)time(0)); //Start random generator

vector <CARD> Cards; //Declare cards vector

for (int i = 1 ; i <= 52 ; i++ )
{
Cards.push_back(i); //Fill Cards with values 1-52
}

//Print original sequence
cout << &quot;Original deck: (&quot; << endl;
for (vector <CARD>::iterator Iter1 = Cards.begin( ) ; Iter1 != Cards.end( ) ; Iter1++ )
cout << *Iter1 << &quot; &quot;;
cout << &quot;)&quot; << endl;

//Shuffle sequence
random_shuffle( Cards.begin(), Cards.end() );
//Works no problem

//Print shuffled sequence
cout << &quot;Cards shuffled. New order: (&quot; << endl;
for (vector <CARD>::iterator Iter2 = Cards.begin( ) ; Iter2 != Cards.end( ) ; Iter2++ )
cout << *Iter2 << &quot; &quot;;
cout << &quot;)&quot; << endl;

//TODO: Hand cards out to players.
}

How do I seed the random_shuffle() so it doesn't rearrange Cards in the same order every run?

I tried using:
//Shuffle sequence
random_shuffle( Cards.begin(), Cards.end(), rand() );
error C2664: 'std::random_shuffle' : cannot convert parameter 3 from 'int' to 'int &'
A reference that is not to 'const' cannot be bound to a non-lvalue

tried:
//Shuffle sequence
int random_num = rand();
random_shuffle( Cards.begin(), Cards.end(), random_num );
error C2064: term does not evaluate to a function taking 1 arguments

It's probabaly some stupid error that i missed...
 
The third parameter of random_shuffle is a function that should be called to generate a random number.

When you say:

random_shuffle( Cards.begin(), Cards.end(), rand() );

you're trying to pass a random number as the third parameter. That is, you're passing the result of the function, not the function itself.


You meant to say:

random_shuffle( Cards.begin(), Cards.end(), rand );

i.e., don't call the function, just pass it in.
 
With &quot;rand&quot; as the 3rd argument it wouldn't compile.

I used another random generating function:

int random(int limit)
{
return rand()%limit;
}

and IT worked, thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top