13.8. Subdecks

How should we represent a hand or some other subset of a full deck? One easy choice is to make a Deck object that has fewer than 52 cards.

We might want a function, subdeck, that takes a vector of cards and a range of indices, and that returns a new vector of cards that contains the specified subset of the deck:

Deck Deck::subdeck (int low, int high) const {
  Deck sub (high - low + 1);

  for (size_t i = 0; i < sub.cards.size(); i++) {
    sub.cards[i] = cards[low + i];
  return sub;

To create the local variable named subdeck we are using the Deck constructor that takes the size of the deck as an argument and that does not initialize the cards. The cards get initialized when they are copied from the original deck.

The length of the subdeck is high - low + 1 because both the low card and high card are included.


This sort of computation can be confusing and can lead to “off-by-one” errors. Drawing a picture is usually the best way to avoid them.

As an exercise, write a version of findBisect that takes a subdeck as an argument, rather than a deck and an index range. Which version is more error-prone? Which version do you think is more efficient?

Try writing the findBisect function in the commented section of the active code below. If done correctly, the program should output that the Seven of Clubs is at index 6 and the King of Diamonds is at index -1. If you get stuck, you can reveal the extra problem at the end for help.

You have attempted of activities on this page