In C++, erasing elements from a `std::vector` while iterating can lead to issues like invalidating iterators, which may result in undefined behavior. To manage this safely and efficiently, you can use techniques such as the `erase-remove` idiom, or use reverse iteration. Below, we provide a code example illustrating how to safely erase elements from a vector during iteration.
#include
#include
#include
int main() {
std::vector myVector = {1, 2, 3, 4, 5, 6};
// Using erase-remove idiom
myVector.erase(std::remove_if(myVector.begin(), myVector.end(),
[](int value) { return value % 2 == 0; }),
myVector.end());
for (int value : myVector) {
std::cout << value << " "; // Output: 1 3 5
}
std::cout << std::endl;
// Alternative: Reverse iteration
for (auto it = myVector.rbegin(); it != myVector.rend(); ) {
if (*it % 2 == 0) {
it = std::vector::reverse_iterator(myVector.erase((it + 1).base()));
} else {
++it;
}
}
for (int value : myVector) {
std::cout << value << " "; // Output: 1 3 5
}
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?