A deck is an ordered collection of playing cards from which cards can be drawn or shuffled. A standard deck contains 52 cards: four suits with 13 values each, from ace through the court cards. section 5.0 section 5.1
A C++ deck implementation can be built in stages:
- Represent each card with a suit and value, then store the complete deck in std::array<Card, 52> because its size is known at compile time. section 5.1 section 5.1.5
- Create every suit–value combination, access cards with operator[], and shuffle the array with std::ranges::shuffle and an mt19937 generator seeded by random_device. section 5.1.5 section 5.2.1
- Extend the deck to 54 elements by placing two jokers in an array of std::variant<Card, Joker> and copying the standard cards after them. section 5.2.4
Higher-or-lower game
Shuffle the deck, show the current card, and ask whether the next card is higher or lower. Compare adjacent cards, stop after an incorrect guess or at the end, and report the number guessed correctly. A joker makes either comparison a free turn. section 5.2.2 section 5.2.4
Listing 5.17 Building a deck of cards
std::array<Card, 52> create_deck()
{
std::array<Card, 52> deck;
auto card = deck.begin(); #1
for (auto suit :
{Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades}) #2
{
for (int value = 1; value <= 13; value++) #3
{
*card = Card{ FaceValue(value), suit }; #4
++card; #5
}
}
return deck;
}
The complete deck-building listing shows how fixed storage, suit iteration, value iteration, card construction, and sequential filling work together. section 5.1.5
