0

Im trying to make a class CardDeck with the constructor vector<Card> CardDeck

My Card class looks like this

Card.h file:

enum Suit{clubs = 0, diamonds, hearts, spades};

enum Rank{two = 2, three, four, five, six, seven, eight,
                nine, ten, jack, queen, king, ace};

class Card{
private:
    Suit s;
    Rank r;
public:
    Card(Suit suit, Rank rank)
        :s{suit}, r{rank} {};
    Suit getSuit() const;
    Rank getRank() const;
    string toString() const;
    string toStringShort() const;
};

I now want to make a CardDeck class that will construct the vector cards inside CardDeck

CardDeck.h file:

#include "Card.h"

class CardDeck
{
private:
    vector<Card> cards{}; //Where I'm stuck
public:
//...
};

Is there a way to loop through all Suits and Ranks like this

Pseudocode:

for s in Suits:
    for r in Ranks:
        cards.push_back(Card{s, r})

1 Answers1

0

Since your using an enum you can use integers to get it done,

for (int i = 0; i < 4; i++)    // Suit
    for(int j = 2; j < 15; j++)    // Rank
        cards.push_back(Card{static_cast<Suit>(i), static_cast<Rank>(j)});

If you don't know how enums work, they are just like const integers. They just have a name which makes it easier to access and use (also safe if you may). Another property is that it increases the value as it goes up,

enum Count {
    Zero,    // Default is 0.
    One,     // Since the before one is 0, this is 1.
    Two,     // Since the before one is 1, this is 2.
    Three    // Since the before one is 2, this is 3.
};

See the pattern? And since the underlying type of an enum is an integer, you can use int to assign values to your constructor.

Bonus: You can state the enums integer type like this,

enum Counter : long long { ... };
D-RAJ
  • 3,263
  • 2
  • 6
  • 24