ProblemsSTL MasteryThe postfix tax
NoviceSTL Mastery

The postfix tax

Context

A simple summation loop is slow. The reason: it++ in the loop. Postfix returns the old iterator value, so it copies the iterator on every step — and this iterator carries a 512-byte buffer in each copy. Nobody even uses the value it++ returns.

Task

The loop uses it++. Postfix increment always makes a copy of the iterator — it has to return the old value. This iterator is expensive to copy. Change the loop so it makes zero copies; the test checks the copy counter.

Constraints

  • The sum must stay correct
  • Traversal must make zero iterator copies (the iterator counts them — the test asserts the counter)
  • Do not bypass the iterator (no raw pointer loop over the data)
  • HeavyIterator itself stays unchanged — fix only the traversal

Before you code

  • Why must operator++(int) return the previous value, and why does that force a copy?
  • When the result of it++ is not used, what may the compiler still NOT optimize away, and why?
  • Where does postfix increment genuinely belong?

Tests

  • #1Sum is correct
  • #2Traversal makes zero iterator copies

Hints

Hint 1

Postfix it++ must hand back the value from before the step. Where can it take that value from, if not a copy?

Hint 2

When nobody reads the result of the increment, the form is your choice — and one form never copies.

Editorpostfix-increment-tax.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.