Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a data structure while iterating over it

Tags:

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 << " .. ";     } } 
like image 937
user620189 Avatar asked Apr 12 '11 16:04

user620189


People also ask

Can I modify list while iterating?

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.

Can we add elements while iterating?

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.

How do you append elements to a list while iterating over the list in Python?

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.


1 Answers

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() { ... } 
like image 146
Lightness Races in Orbit Avatar answered Sep 23 '22 19:09

Lightness Races in Orbit