0

I am trying to create a deck of cards in C++. I store that deck in an array array<Card, 52> deckOfCards = generateCards(). Once I create the array, is there any way to shuffle the objects inside of it easily? For example, in Java, you could use the shuffle() algorithm and the objects would be shuffled.


People have mentioned the usage of random_shuffle in the comment, however random_shuffle has been deprecated since C++14, and removed since C++17.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
HadiB
  • 36
  • 6
  • 3
    Have a look at [`std::random_shuffle`](https://en.cppreference.com/w/cpp/algorithm/random_shuffle). – Wais Kamal Nov 21 '21 at 19:22
  • dup: https://stackoverflow.com/a/14720159/4641116 – Eljay Nov 21 '21 at 19:22
  • 3
    @WaisKamal at this point I'd recommend recommending `shuffle`, not `random_shuffle`. As you can see in the very documentation you linked, `random_shuffle` was deprecated and removed. – Fureeish Nov 21 '21 at 19:23
  • how do you implement it, could you please provide an example because when I add `#include ` and attempt to call `random_shuffle(deckOfCards)` i get a `No matching function for call to 'random_shuffle` red line in clion – HadiB Nov 21 '21 at 19:27
  • @HadiB did you read the linked documentation and the examples below it? – Fureeish Nov 21 '21 at 19:28

1 Answers1

3

Yes, C++ does have a shuffle() function. However, you must also add a random generator in there manually, which could be daunting at a first glance. However, if you don't really care the exact generator and engine being used, then this could be done simply with:

std::shuffle(deckOfCards.begin(), deckOfCards.end(), std::default_random_engine{/*optional seed*/});

or

std::shuffle(deckOfCards.begin(), deckOfCards.end(), std::random_device{});

Where the first one is deterministic and the second one is non-deterministic.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ranoiaetep
  • 5,872
  • 1
  • 14
  • 39