13.4. Another constructor¶
Now that we have a card_deck object, it would be useful to initialize the
cards in it. From the previous chapter we have a function called
build_deck that we could use (with a few adaptations), but it might
be more natural to write a second card_deck constructor.
card_deck::card_deck () {
std::vector<playing_card> temp (52);
cards = temp;
std::size_t i = 0;
for (int m_suit = clubs; m_suit <= spades; ++m_suit) {
for (int m_rank = ace; m_rank <= king; ++m_rank) {
cards[i].m_suit = static_cast<card_suit>(m_suit);
cards[i].m_rank = static_cast<card_rank>(m_rank);
i++;
}
}
}
Notice how similar this function is to build_deck, except that we had
to change the syntax to make it a constructor. Now we can create a
standard 52-card deck with the simple declaration card_deck deck;
The active code below prints out the cards in a deck using the loop from the previous section.
1#include <cstddef>
2#include <iostream>
3#include <string>
4#include <vector>
5
6enum card_suit { clubs, diamonds, hearts, spades };
7
8enum card_rank { ace=1, two, three, four, five, six, seven, eight, nine,
9ten, jack, queen, king };
10
11struct playing_card {
12 card_rank m_rank;
13 card_suit m_suit;
14 playing_card ();
15 playing_card (card_suit s, card_rank r);
16 void print () const;
17};
18
19struct card_deck {
20 std::vector<playing_card> cards;
21 card_deck ();
22};
23
24int main() {
25 card_deck deck;
26 for (std::size_t i = 0; i < 52; i++) {
27 deck.cards[i].print();
28 }
29}
Based on your observations from the active code above, the cards in deck are initialized
to the correct suits and ranks of a standard deck of 52 cards.
Let's write a constructor for a deck of cards that uses 40 cards. This deck uses all 4 suits and ranks Ace through 10, omitting all face cards.
-
i++; } } } -
card_deck::card_deck () { -
cards = temp; std::size_t i = 0; -
cards[i].m_suit = m_rank; cards[i].m_rank = m_suit; -
cards[i].m_suit = static_cast<card_suit>(m_suit); cards[i].m_rank = static_cast<card_rank>(m_rank); -
for (card_rank m_rank = ace; m_rank <= ten; m_rank = card_rank(m_rank+1)) { -
for (card_suit m_suit = clubs; m_suit < spades; m_suit = card_suit(m_suit+1)) { -
for (int m_rank = ace; m_rank <= king; ++m_rank) { -
for (int m_suit = clubs; m_suit <= spades; ++m_suit) { -
std::vector<playing_card> temp (40); -
std::vector<playing_card> temp (52);