Iterating over a `std::deque` in C++ while modifying it can be tricky, especially in embedded systems where stability and performance are critical. It's important to ensure that iterators remain valid throughout the modification process. Here’s how to safely iterate a `std::deque` when you're also modifying it.
One effective method is to use a traditional for-loop and adjust your index accordingly to account for the changes in the container size. This way, you can avoid invalidating iterators:
#include <iostream>
#include <deque>
int main() {
std::deque<int> myDeque = {1, 2, 3, 4, 5};
for (size_t i = 0; i < myDeque.size(); ) {
std::cout << myDeque[i] << std::endl;
if (myDeque[i] % 2 == 0) { // For example, remove even numbers
myDeque.erase(myDeque.begin() + i);
} else {
++i; // Only increment if you do not modify the deque
}
}
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?