how to use stl random_shuffle with seed of your choice on a vector of pointers

I cannot understand why an example of this doesn’t show up anywhere in Google or Google Groups.

Hopefully, you found this page before you wasted as much time as I did searching.

A. Define a functor class like this one: (props to Midgaard, who almost had what I needed).[1]

class RandIntClass
{
public:
RandIntClass() {}
int operator() (int aRange)
{
srand(42);//seed of your choice here
int result = rand() % aRange;
return result;
}
};

B. In your code. Assuming you have a vector of pointers already.
//shuffle set 1 w/ seed 42

#include algorithm (add brackets around ‘algorithm’. wordpress keeps removing them for me.)
RandIntClass Rand;
std::random_shuffle( myVector.begin(), myVector.end(), Rand );

That should do it.
I tested this with two identical vectors. I shuffled each one independently, and they came out in the same order.

I have no idea why zero of the major stl tutorials out there couldn’t put this example together. I hate it when examples only use primitives or they only used the time(NULL) example.

Anyway, hope this helps. Enjoy,

Ed

If you are on gcc, watch out for this gotcha with srand48:

http://gcc.gnu.org/ml/libstdc++/2000-08/msg00015.html

[1] http://home20.inet.tele.dk/midgaard/tipc20050110.html

This entry was posted in Tips. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *