What happens when you add elements to a data structure such as a vector while iterating over it. Can I not do this?
I tried this and it breaks:
int main() { vector<int> x = { 1, 2, 3 }; int j = 0; for (auto it = x.begin(); it != x.end(); ++it) { x.push_back(j); j++; cout << j << " .. "; } }
The general rule of thumb is that you don't modify a collection/array/list while iterating over it. Use a secondary list to store the items you want to act upon and execute that logic in a loop after your initial loop.
You can't modify a Collection while iterating over it using an Iterator , except for Iterator. remove() . This will work except when the list starts iteration empty, in which case there will be no previous element. If that's a problem, you'll have to maintain a flag of some sort to indicate this edge case.
Use the Python List append() method to append elements to a list while iterating over the list using a for-in loop. If you append a new element to the list while iterating the list results in a list containing the original list's elements and the new elements.
Iterators are invalidated by some operations that modify a std::vector
.
Other containers have various rules about when iterators are and are not invalidated. This is a post (by yours truly) with details.
By the way, the entrypoint function main()
MUST return int
:
int main() { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With