How do I erase elements while iterating with std::deque in performance-sensitive code?

When working with std::deque in C++, erasing elements while iterating through the container can be tricky, especially in performance-sensitive applications. Directly erasing elements within a loop could lead to invalidated iterators and potentially inefficient performance. To handle this properly, it's essential to use a backwards iteration, or store the indices of the items to erase, or employ the std::remove_if algorithm combined with the erase member function. Below is an example on how to do this effectively:

#include #include #include int main() { std::deque numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Use std::remove_if to remove even numbers auto new_end = std::remove_if(numbers.begin(), numbers.end(), [](int n) { return n % 2 == 0; }); // Erase the removed elements numbers.erase(new_end, numbers.end()); // Display the remaining elements for (const auto& number : numbers) { std::cout << number << " "; } std::cout << std::endl; return 0; }

C++ std::deque erase elements performance-sensitive code remove_if iterator invalidation