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.

Example c192_12_7
 1#include <cstddef>
 2#include <iostream>
 3#include <string>
 4#include <vector>
 5
 6struct playing_card {
 7    int suit, 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 suit = 0; suit <= 3; suit++) {
18        for (int rank = 1; rank <= 13; rank++) {
19            deck[i].suit = suit;
20            deck[i].rank = 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 suit = 0; suit <= 3; suit++) {
      for (int rank = 1; rank <= 13; rank++) {
        if (rank == 1 || rank >= 9){
          deck[i].suit = suit;
          deck[i].rank = rank;
          i++;
        }
      }
  }
  return deck;
}