12.7. The print_deck functionΒΆ
Whenever you are working with vectors, it is convenient to have a function that prints the contents of the vector. We have seen the pattern for traversing a vector several times, so the following function should be familiar:
void print_deck (const std::vector<playing_card>& deck) {
for (std::size_t i = 0; i < deck.size(); i++) {
deck[i].print ();
}
}
By now it should come as no surprise that we can compose the syntax for vector access with the syntax for invoking a function.
Since deck has type vector<playing_card>, an element of deck has
type playing_card. Therefore, it is legal to invoke print on
deck[i].
A Euchre card_deck contains 9's, 10's, Jacks, Queens, Kings, and Aces of all four suits.
Modify the build_deck function below to create a Euchre deck. The print_deck
function will allow you to verify that you have done this correctly.
1#include <cstddef>
2#include <iostream>
3#include <string>
4#include <vector>
5
6struct playing_card {
7 int m_suit, m_rank;
8
9 playing_card ();
10 playing_card (int s, int r);
11 void print () const;
12};
13
14std::vector<playing_card> build_deck() {
15 std::vector<playing_card> deck (52);
16 std::size_t i = 0;
17 for (int m_suit = 0; m_suit <= 3; m_suit++) {
18 for (int m_rank = 1; m_rank <= 13; m_rank++) {
19 deck[i].m_suit = m_suit;
20 deck[i].m_rank = m_rank;
21 i++;
22 }
23 }
24 return deck;
25}
26
27void print_deck(const std::vector<playing_card>& deck);
28
29int main() {
30 std::vector<playing_card> deck = build_deck();
31 print_deck(deck);
32}
Hopefully you took some time to try and figure out the code yourself. The solution below is just one of several correct solutions for creating the Euchre deck:
std::vector<playing_card> build_euchre_deck() {
std::vector<playing_card> deck (24);
std::size_t i = 0;
for (int m_suit = 0; m_suit <= 3; m_suit++) {
for (int m_rank = 1; m_rank <= 13; m_rank++) {
if (m_rank == 1 || m_rank >= 9){
deck[i].m_suit = m_suit;
deck[i].m_rank = m_rank;
i++;
}
}
}
return deck;
}