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