ProblemsUB & GotchasThe loop that eats its own tail
NoviceUB & Gotchas

The loop that eats its own tail

Context

The function appends a correction to the end of the vector for every negative reading. On three test elements it worked. On real data the vector grew during the loop, moved to new memory — and the loop kept reading the old memory. range-for takes begin() and end() once, at the start, and never re-checks them.

Task

The function does push_back into the vector while a range-for loop iterates that same vector. When the vector grows, its memory moves — and the loop keeps walking the old, freed memory. Rewrite the loop; for every negative element it must still append -x at the end.

Constraints

  • For every negative element of the original content, append -x once, in original order
  • Corrections themselves are positive and must not be re-processed
  • Do not iterate a container you are growing (no range-for over v while pushing into it)
  • Keep the signature unchanged; the original elements stay in place

Before you code

  • Which operations invalidate std::vector iterators, and why does reallocation invalidate all of them?
  • Why did the three-element demo "work"?
  • Why does snapshotting v.size() before the loop also stop corrections from being re-processed?

Tests

  • #1Corrections are appended in order
  • #2Survives forced reallocations (1000 readings)
  • #3Positives and zeros get no corrections

Hints

Hint 1

Range-for is sugar for auto it = v.begin(); it != v.end(); captured once. Ask yourself what those two iterators point at after a reallocation.

Hint 2

You only need to examine the elements that existed before the loop started — fix that count first, then index.

Editorpush-back-during-range-for.cpp
Results

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