Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Iterator Invalidation Rules | Iterators with Algorithms
Practice
Projects
Quizzes & Challenges
Quizer
Challenges
/
C++ STL Iterators

bookIterator Invalidation Rules

Sveip for å vise menyen

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

main.cpp

copy
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.

question mark

Which operation can invalidate all iterators to a std::vector?

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 5

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 4. Kapittel 5
some-alt