John
John

Reputation: 1594

How to populate a deck class with instances of a card class? c++

I have a program for which I have created a simple card class. How can I create and populate a deck of playing cards?

Upvotes: 0

Views: 1139

Answers (3)

CashCow
CashCow

Reputation: 31445

The simplest way is a conversion from an int to a card such that each number from 0-51 yields a unique card. It doesn't really matter how, as long as they are all unique.

Then you can create a deck of cards from each number in a loop, possibly into a vector, and you can perform std::random_shuffle to shuffle a deck.

If you want your deck of cards to remain "generic" as to what game is going to be played then do not make features member functions of the card but "free" functions. e.g. the ace of spades may outrank the 7 of spades at Bridge but that is a feature of Bridge (and Whist related games), not of cards in general. Similarly a card, or deck, has no concept of "trumps".

You might want a special card option for a joker. Of course games that don't use jokers wouldn't allow one of these in the deck.

Upvotes: 0

slashmais
slashmais

Reputation: 7155

This is to extend mathematician1975's answer with an example:

#include <iostream>
#include <string>
#include <map>
#include <array> //needs c++11 support

enum CARDSUIT { Spades, Hearts, Diamonds, Clubs };
typedef std::pair< int, int > Card;
template< class T, size_t N> struct DECK : public std::array< T, N> 
{
    void shuffle()
    {
        //see here for example:
        // http://www.cplusplus.com/reference/algorithm/random_shuffle/
    }
};
typedef DECK<Card, 52> StandardDeck;

int main()
{
    int i=0,j=0;
    StandardDeck deck;

    for (i=Spades; i<=Clubs; i++)
        for (j=0; j<13; j++)
                deck[j + (i*13)] = Card(i,j);

    for (i=0; i<(int)deck.size(); i++) 
        std::cout << deck[i].first << " " << deck[i].second << "\n";

    return 0;
}

Upvotes: 0

mathematician1975
mathematician1975

Reputation: 21351

If you have a class for card simply create a class for deck which among other things contains a data structure (such as std::vector or an array) to contain the card objects. Then implement functions such as deal , shuffle etc or whatever you feel appropriate.

To populate your deck, you could use an add_card function. You can then use this to loop over all suits and values to create a card of each distinct suit/value type and add it to your deck. Alternatively (or additionally), you could do this in the deck constructor, but having an add_card function will allow your deck to model different types of decks such as individual card hands or multiple deck games such as casino blackjack for example.

If you use a container from the standard C++ library that supports random access iterators, you could make use of the std::random_shuffle function to shuffle your deck

EDIT: updated to incorporate some of the points raised in comments

Upvotes: 3

Related Questions