Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ イテレータの無効化と安全性 | STLのイントロダクション
C++ STLコンテナとアルゴリズム

bookイテレータの無効化と安全性

メニューを表示するにはスワイプしてください

イテレータが無効になる仕組みを理解することは、STLコンテナやアルゴリズムを用いた信頼性の高いC++コードを書く上で不可欠です。イテレータの無効化は、一度有効な要素を指していたイテレータが、コンテナの変更後に安全に使用できなくなる現象です。これにより、未定義動作やクラッシュ、原因が特定しにくいバグが発生する可能性があります。

  • std::vectorに要素を追加または削除すると、特に再割り当てが発生した場合にイテレータが無効になることがあります。
  • inserteraseresizeなどの操作は、コンテナの種類によってイテレータの有効性に異なる影響を与えます。
  • std::listのようなコンテナは、挿入や削除の際にイテレータの有効性を保持することが多いです。

イテレータの無効化は、コンテナの構造や内容を変更する操作の後に発生します。具体的な挙動は、コンテナの種類と実行された操作によって異なります。

main.cpp

main.cpp

copy
1234567891011121314151617181920212223242526
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; // Obtain an iterator to the second element auto it = numbers.begin() + 1; // Insert a new element at the beginning numbers.insert(numbers.begin(), 0); // 'it' may now be invalidated due to possible reallocation // Accessing *it is unsafe std::cout << "Possible invalid iterator value: "; std::cout << *it << std::endl; // Undefined behavior // Erase an element and try to use the iterator again it = numbers.begin() + 2; numbers.erase(numbers.begin() + 1); // 'it' still points to the old position, which may now be invalid std::cout << "After erase, possible invalid iterator value: "; std::cout << *it << std::endl; // Undefined behavior }
Note
注意

STLアルゴリズムを使用する際は、イテレータの無効化を引き起こす可能性のある操作に注意が必要です。無効化されたイテレータを使用すると、プログラムの安全性や正確性が損なわれることがあります。

question mark

次のうち、std::vector のすべてのイテレータが無効になる可能性が最も高い操作はどれですか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  3
some-alt