When working with std::forward_list
in C++, iterator invalidation can occur when you modify the list. It's important to handle this correctly to avoid runtime errors. The following strategies can help you manage iterator validity:
std::forward_list::insert_after
for insertions and std::forward_list::erase_after
for deletions.Here’s an example demonstrating iterator handling with std::forward_list
:
#include <forward_list>
#include <iostream>
int main() {
std::forward_list my_list = {1, 2, 3, 4, 5};
// Correct insertion method
auto it = my_list.insert_after(my_list.before_begin(), 0);
// Iterate safely
for (auto iter = my_list.begin(); iter != my_list.end(); ) {
if (*iter % 2 == 0) {
iter = my_list.erase_after(std::prev(iter)); // Erase safely
} else {
++iter; // Only increment if not erased
}
}
// Print remaining elements
for (const auto& value : my_list) {
std::cout << value << " ";
}
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?