How to pick 5 random cards from a 52‑card deck in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm> // shuffle

/*
A standard deck of 52 playing cards consists of four suits: 
spades (♠), hearts (♥), diamonds (♦), and clubs (♣). 

Each suit contains 13 ranks, which are Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King.

Cards of spades and clubs are black, while hearts and diamonds are red.

Color is informational only — it does not affect shuffling or random selection.
*/

/*
    This program picks 5 random cards from a standard 52-card deck.
    It uses:
    - std::vector for the deck
    - std::shuffle for efficient randomization
    - std::mt19937 for high-quality randomness
*/

std::vector<std::string> buildDeck() {
    // Ranks and suits of a standard deck
    const std::vector<std::string> ranks = {
        "2","3","4","5","6","7","8","9","10","J","Q","K","A"
    };
    const std::vector<std::string> suits = {
        "Clubs", "Diamonds", "Hearts", "Spades"
    };

    std::vector<std::string> deck;
    deck.reserve(52); // Efficient: avoid reallocations

    // Build the deck: 13 ranks × 4 suits
    for (const auto& suit : suits) {
        for (const auto& rank : ranks) {
            deck.push_back(rank + " of " + suit);
        }
    }

    return deck;
}

int main() {
    // Build the deck
    std::vector<std::string> deck = buildDeck();

    // Create a random engine using a non-deterministic seed
    std::random_device rd;
    std::mt19937 gen(rd());

    // Shuffle the deck
    std::shuffle(deck.begin(), deck.end(), gen);

    // Draw the first 5 cards
    std::cout << "Your 5 random cards:\n";
    for (int i = 0; i < 5; ++i) {
        std::cout << deck[i] << "\n";
    }
}



/*
run:

Your 5 random cards:
4 of Clubs
A of Spades
A of Hearts
3 of Diamonds
A of Clubs

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz
...