Randomize STL stack

Z

Zaphod

I'm using an STL stack to hold objects. I need to randomize the
contents of the stack. Is there a simple way to do this?

thanks
 
M

Marvin - The Paranoid Android

Zaphod said:
I'm using an STL stack to hold objects. I need to randomize the
contents of the stack. Is there a simple way to do this?

Simplicity is relative.
There is no standard way to do that.
You need to roll an algorithm yourself. It would probably involve copying
contents of the stack into a new one, I'm afraid.

Given your stack is std::vector based, you could for example quickly pick
out indices for copying using rand(). It all depends on what degree of
randomness you expect.

Just off the top of my head... There are better approaches, I'm sure.

Cheers
b
 
P

Petec

Zaphod said:
I'm using an STL stack to hold objects. I need to randomize the
contents of the stack. Is there a simple way to do this?

thanks

Try a std::deque container and the std:random_shuffle algorithm.
std::stack is just a wrapper around std::deque that has less features,
enforcing usage as a stack only.

- Pete
 
A

Andrew Koenig

I'm using an STL stack to hold objects. I need to randomize the
contents of the stack. Is there a simple way to do this?

If there were, then in what sense would you consider it to be a stack?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top