Reputation: 1175
I find myself iterating over a container X that is being modified inside the loop. But in each iteration, the unmodified X is needed:
for (int x : X) { // wrong, container X in iteration should be the "original"
modify_X(); // X modified here
}
A solution is to iterate over a copy
containerT X_copy(X);
for (int x : X_copy) {
modify_X();
}
or
for (int x : containerT {X}) {
modify_X();
}
Is there an idiomatic way of doing this?
Upvotes: 1
Views: 112
Reputation: 60440
The last example in your question looks the simplest. However, from C++20, you could also do this:
for (auto copy = X; int i : copy)
{
modify_X();
}
Here's a demo.
Note that in your first snippet, it's not only logically wrong, but it also invokes undefined behavior, as you are modifying a range that you're iterating over.
Upvotes: 3