Skip to main content
Contents
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 13.4 Another constructor
Now that we have a
Deck
object, it would be useful to initialize the cards in it. From the previous chapter we have a function called
buildDeck
that we could use (with a few adaptations), but it might be more natural to write a second
Deck
constructor.
Deck::Deck() {
vector<Card> temp (52);
cards = temp;
int i = 0;
for (Suit suit = CLUBS; suit <= SPADES; suit = Suit(suit+1)) {
for (Rank rank = ACE; rank <= KING; rank = Rank(rank+1)) {
cards[i].suit = suit;
cards[i].rank = rank;
i++;
}
}
}
Notice how similar this function is to
buildDeck
, 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
Deck deck;
Listing 13.4.1. This active code prints out the cards in a deck using the loop from the previous section.
Checkpoint 13.4.1 .
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.
True - we used the buildDeck function with a few modifications to do this.
How do we create the deck?
True - we wrote a Deck constructor to do this.
The for loops in the Deck constructor initialize each card to its proper value.
False - we used the buildDeck function with a few modifications to do this.
Look at the active code. How do we create the deck?
False - we wrote a Deck constructor to do this.
Look at the active code.
Checkpoint 13.4.2 .
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.
Deck::Deck() {
---
vector<Card> temp (40);
---
vector<Card> temp (52); #paired
---
cards = temp;
int i = 0;
---
for (Suit suit = CLUBS; suit <= SPADES; suit = Suit(suit+1)) {
---
for (Suit suit = CLUBS; suit < SPADES; suit = Suit(suit+1)) { #paired
---
for (Rank rank = ACE; rank <= TEN; rank = Rank(rank+1)) {
---
for (Rank rank = ACE; rank <= KING; rank = Rank(rank+1)) { #paired
---
cards[i].suit = suit;
cards[i].rank = rank;
---
cards[i].suit = rank;
cards[i].rank = suit; #paired
---
i++;
}
}
}
You have attempted
of
activities on this page.