Iterating over a container while modifying it can lead to undefined behavior in C++. This is a common problem for developers working with performance-sensitive code. Using std::deque
in C++, it’s important to ensure safe iteration even when you're adding or removing elements. One reliable way to do this is to maintain a separate list of elements to process, which minimizes issues when adding or removing elements during iteration.
Here's a simple example that demonstrates how to safely iterate over a std::deque
while modifying it:
#include <iostream>
#include <deque>
int main() {
std::deque myDeque = {1, 2, 3, 4, 5};
// Create a temporary deque for modification
std::deque toAdd;
for (auto it = myDeque.begin(); it != myDeque.end(); /* no increment here */) {
// Example condition to modify container
if (*it % 2 == 0) {
toAdd.push_back(*it * 10); // Add 10x of even elements to the temporary deque
it = myDeque.erase(it); // safely erase and move the iterator forward
} else {
++it; // Increment only if no modification has happened
}
}
// Now add new elements to original deque
myDeque.insert(myDeque.end(), toAdd.begin(), toAdd.end());
// Printing the modified deque
for (const auto& val : myDeque) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?