ProblemsSTL MasteryAll or nothing
AdvancedSTL Mastery

All or nothing

Context

The function recalculates prices in a catalog. The conversion can throw — bad input, overflow. After one such throw the catalog ended up half in old prices, half in new, and nobody could tell which half. Restarting does not help: the data is already inconsistent. The function must not touch the vector until it knows the whole conversion succeeds.

Task

mapInPlace applies op to every element of the vector. If op throws midway, the vector is left half-transformed — first elements new, the rest old. Rewrite it with the all-or-nothing guarantee: either every element is transformed, or the vector stays exactly as it was. The exception must still reach the caller.

Constraints

  • On success: every element replaced by op(element), in order
  • If op throws: the vector keeps its original content, element for element
  • The exception propagates to the caller (do not swallow it)
  • Keep the signature unchanged

Before you code

  • Why can you not "undo" the applied half after catching the exception? (op may be irreversible)
  • Where can the intermediate results live so the original stays intact?
  • What does the standard call this level of exception safety?

Tests

  • #1Transforms every element on success
  • #2A midway throw leaves the vector untouched
  • #3A throw on the LAST element also rolls back

Hints

Hint 1

Do not write into v at all while op can still throw. Collect the results somewhere else first.

Hint 2

Once every op(x) has succeeded, replacing the whole content of v in one step is cheap — vectors move.

Editorall-or-nothing-transform.cpp
Results

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