Iterator Invalidation Rules
Deslize para mostrar o menu
Iterator invalidation happens when a container operation makes existing iterators, references, or pointers unsafe to use, leading to undefined behavior if accessed.
Iterator invalidation occurs during operations like insertion, erasure, or resizing, and the rules vary by container. For example, std::vector operations may invalidate iterators due to reallocation, while associative containers such as std::map follow different rules. Understanding these differences is essential for writing safe STL code.
main.cpp
1234567891011121314151617181920212223242526#include <iostream> #include <vector> int main() { std::vector<int> v{10, 20, 30, 40, 50}; auto it = v.begin() + 2; // Points to 30 std::cout << "Before insertion: " << *it << std::endl; // Insert at the beginning; may cause reallocation v.insert(v.begin(), 5); // Try to use the old iterator std::cout << "After insertion: "; try std::cout << *it << std::endl; // Undefined behavior if reallocation occurred catch (...) std::cout << "Iterator invalidated!" << std::endl; // Erase an element and check iterator auto it2 = v.begin() + 3; // Should point to what was 30 v.erase(v.begin() + 1); // Remove 20 std::cout << "Value at new iterator: " << *it2 << std::endl; // May be invalid }
This example shows how std::vector operations can invalidate iterators. Inserting an element may reallocate the vector's storage, invalidating all existing iterators. Erasing an element invalidates iterators at or after the erase position because elements are shifted. In both cases, using invalidated iterators results in undefined behavior.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo