Insight 24.7.1.
Anytime you want to keep track of a piece of information during recursion, you can add it as an additional parameter.
countZeros function. It is destructive. It will remove all of the values from the vector we give it. (That is why the parameter was not const).
const reference instead. To do this, we would have to change the code to make a copy of the starting vector, remove the last item from the copy, and pass that copy as the parameter:
int countZeros(const vector<int>& numbers) {
if (numbers.empty()) {
return 0;
} else {
int lastElement = numbers.back();
vector<int> copy = numbers; // create a copy
copy.pop_back(); // remove last element from the copy
int count = countZeros(numbers);
if (lastElement == 0) {
count = count + 1;
}
return count;
}
}
{5, 3, 0, 2, 0, 1}, we would make a copy that just had {5, 3, 0, 2, 0}, then another that had, {5, 3, 0, 2}, and so on....
size_t as the type:
int countZeros(const vector<int>& numbers, int curIndex);
if (curIndex == numbers.size()) {
return 0;
}
curIndex of 0, we can ask someone else to look at curIndex of 1 and use their answer to learn about the rest of the vector. That person would ask someone else to look at index 2. Each recursive step will increase the current index.
countZeros just got more complex. main has to pass in 0 as the starting index:
countZeros(numbers, 0);
countZeros(numbers) and have it work.
curIndex have a default value:
int countZeros(const vector<int>& numbers, size_t curIndex = 0);
countZeros which takes the vector and then calls the recursive countZeros with the correct parameters:
int countZeros(const vector<int>& numbers) {
return countZeros(numbers, 0); //start recursion with extra params
}
countZeros(numbers);
countZeros function count down from the last index of the vector to the beginning. Starting that process might look like countZeros(myVector, myVector.size() - 1).