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

bookIterator Invalidation Rules

Veeg om het menu te tonen

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

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 4. Hoofdstuk 5

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 4. Hoofdstuk 5
some-alt