How do I avoid iterator invalidation with std::forward_list?

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:

  1. Use the correct methods: Use methods that do not invalidate iterators, such as std::forward_list::insert_after for insertions and std::forward_list::erase_after for deletions.
  2. Reassign iterators: If you need to erase elements, reassign iterators to ensure they point to valid elements after the operation.
  3. Avoid removing elements while iterating: Instead of removing elements during iteration, consider marking elements for removal and performing clean-up in a separate pass.

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

C++ std::forward_list iterator invalidation container C++ programming