Iterating through a std::vector in C++ while erasing elements can be problematic, especially for large datasets. This is because removing elements can invalidate the iterator and lead to undefined behavior. To safely erase elements while iterating, you can use the erase-remove idiom or manually adjust the iterator. Here’s how you can do it:
iterating, std::vector, erase, elements, C++, large datasets, erase-remove idiom
This guide describes effective methods to iterate and erase elements in std::vector for large datasets without causing errors or performance issues.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Using the erase-remove idiom
v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end());
// Output the remaining elements
for (int x : v) {
std::cout << x << " ";
}
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?