简体   繁体   中英

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:

  • No match for 'operator-' in '__i- __first'
  • No match for 'operator!=' in '__first != __last'
  • No match for 'operator+' in '__first + 1'
  • No match for 'operator++' in '++ __i'

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.

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.

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);

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM