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.
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.
-x once, in original orderv while pushing into it)std::vector iterators, and why does reallocation invalidate all of them?v.size() before the loop also stop corrections from being re-processed?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.
You only need to examine the elements that existed before the loop started — fix that count first, then index.
Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.