Roman Rdgz
Roman Rdgz

Reputation: 13254

std::random_shuffle with a std::queue

How can I apply the std::random_shuffle algorithm with a std::queue? I tried this:

std::random_shuffle(myQueue.front(), myQueue.back());

And gives errors:

My queue is holding Card classes, which represent poker cards. I can understand that the error comes from the operations which std::random_shuffle is doing with the queue elements So, even when I don't need a != operator for my Card class, i wrote one and that error is gone.

But what should I do with the rest of the errors? It makes no sense to write operators +, - and ++ for a Card class.

Upvotes: 0

Views: 4859

Answers (3)

Mike Seymour
Mike Seymour

Reputation: 254531

std::queue is not a container; it's a container adapter. It adapts a sequence container to restrict its interface to simple queue/dequeue operations. In particular, it doesn't let you (easily) iterate over the underlying container, which is what std::random_shuffle needs to do. If you don't want those restrictions, don't use std::queue; use a sequence container (such as vector or deque) directly.

There are ways to subvert its interface and meddle with the underlying container, but it would be much better to choose an appropriate container to start with.

Upvotes: 6

juanchopanza
juanchopanza

Reputation: 227438

std::random_shuffle expects a pair of iterators. Furthermore, an std::queue is not designed to be messed around like that. It maintains the order of its elements by definition. What you can do is create an std::deque, shuffle that, and the construct a queue from it.

std::deque<int> d {5, 1, 67, 89, 32, 444}; // populate in the order you would the queue
std::random_shuffle(d.begin(), d.end());
std::queue<int> q(d);

Upvotes: 3

Claudio
Claudio

Reputation: 1706

std::random_shuffle expects two iterators, but std::queue::front() and std::queue::back() return two references to elements. std::queue does not expose iterators, you it only offers an interface to push back and pop front elements. If you need to iterate over a collection use std::deque (or any of the standard containers).

Upvotes: 1

Related Questions