Find the bug · #35 · Loops and closures Hard C++
Two refunds in a row, only one is removed
A daily report removes refunds before adding up the takings, and back-to-back refunds slip through.
On this page
The report
A daily sales report removes refunds (negative amounts) before adding up the takings. On days with two refunds back to back, one of them is still in the total.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Removes refunds (negative amounts) from a day's transactions.
void removeRefunds(vector<int>& amounts) {
for (size_t i = 0; i < amounts.size(); i++) {
if (amounts[i] < 0) amounts.erase(amounts.begin() + i);
}
}Read it, then pick a line.
After an erase, which element is at index i? Does the loop look at it?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
vector<int> day = {500, -200, -300, 700};
removeRefunds(day);
for (int a : day) cout << a << " ";
cout << endl;It prints
500 -300 700
It should print
500 700
Show the answer: the bug, the fix, and how you’d find it
The bug (lines 3, 4)
Line 4 erases the refund at index i, which slides every later amount one place left. Then the loop’s i++ moves past the amount that just slid into position i, so a refund right after another one is never checked. Use the erase–remove idiom (or only move on when nothing was erased).
The fix
1// Removes refunds (negative amounts) from a day's transactions.2void removeRefunds(vector<int>& amounts) {3 for (size_t i = 0; i < amounts.size(); i++) {4 if (amounts[i] < 0) amounts.erase(amounts.begin() + i);5 }3 amounts.erase(remove_if(amounts.begin(), amounts.end(), [](int a) { return a < 0; }), amounts.end());6}How you’d find it
- Reproduce with two refunds side by side: one of them survives.
- Trace the indices: at i = 1 the -200 is erased and -300 slides to index 1; then i becomes 2, which is 700. The -300 was never checked.
- It’s the same bug as removing from a Python list while looping over it: the index and the data move apart.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
vector<int> v = {-1, -2, -3, 4};
removeRefunds(v);
CHECK(v == vector<int>({4}));Where else this bites
- Erasing through an iterator in a loop: use the iterator
erasereturns. - In C++20,
std::erase_if(v, pred)does it in one call.