How do I iterate safely under modification with std::deque in performance-sensitive code?

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; }

C++ std::deque safe iteration modifying container performance-sensitive code