Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Iterator Invalidation Rules | Iterators with Algorithms
/
C++ STL Iterators

bookIterator Invalidation Rules

Svep för att visa menyn

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

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 5

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 4. Kapitel 5
some-alt