liveBook · Manning

Deck

As explained in Learn C++ by Example

A deck is an ordered collection of playing cards from which cards can be drawn or shuffled.

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

How Learn C++ by Example covers it

How deep it goes
Builds standard and joker-containing decks, explains fixed storage and shuffling, and stops short of reusable shuffle-class design.
Examples
Demonstrates a 52-card array, suit–value generation, two-joker extension, shuffled output, and higher-or-lower gameplay.
What you can do after
Build it from scratch as a fixed-size C++ deck and use it in a shuffled higher-or-lower card game.
How it connects
Connects playing cards with classes, arrays, comparison operators, random shuffling, std::variant, and higher-or-lower games.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.