Codiqo

Learn C++ · lesson 51 of 61 · about 9 minutes

Recursion on Vectors and Strings

Handle one item, then let a recursive call handle the rest.

What you'll learn

  • Recurse over a vector with an index
  • Recurse over a string
  • Pass containers by const reference

The treasure room

At the bottom of the tower is a treasure room. The player types how many chests there are and the gold in each, and the adventure sums them up: Chests: 39 gold in all, the richest has 20. Two recursive functions do the work, each walking the vector of chests with an index: chestTotal adds chest i to the total of the chests after it, and richestChest keeps the bigger of chest i and the richest of the rest.

An index instead of a copy

Making a smaller copy of a vector on every call would be slow. Instead, pass the vector by const reference and an index that says where to start.

The total from index i onwards is v[i] plus the total from i + 1. When i reaches v.size(), there's nothing left, so the total is 0.

Adding up a vector

#include <iostream>
#include <vector>

int total(const std::vector<int>& v, std::size_t i) {
    if (i == v.size()) return 0;
    return v[i] + total(v, i + 1);
}

int main() {
    std::vector<int> nums = {4, 1, 5, 2};
    std::cout << total(nums, 0) << "\n";
}

Output

12

Strings work the same way

A string is a sequence of characters, so the same index trick works. To reverse a string, reverse the rest first, then put the current character on the end. s.substr(1) also gives the rest of a string, which is fine for short text.

Reversing text

#include <iostream>
#include <string>

std::string reverse(const std::string& s) {
    if (s.empty()) return "";
    return reverse(s.substr(1)) + s[0];
}

int main() {
    std::cout << reverse("phoebe") << "\n";
}

Output

ebeohp

A different base case for the biggest

Not every question has an answer for nothing at all. The total of no chests is 0, but there's no richest chest among none. So richestChest stops at the last chest, i == chests.size() - 1, whose richest is itself, and the adventure only calls it when there's at least one chest.

Tip

std::size_t is the type that size() returns. Using it for the index avoids warnings about comparing signed and unsigned numbers.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.