Files
2nd/10_Wiki/Topic_Programming/Topic_CPP/CPP_Iterators.md
T
Antigravity Agent e9cbf23ab5 docs(10_Wiki): Dev 폴더 누락분 반영 — Topic_Programming으로 통합
이전 재구성 작업에서 Dev/ 폴더가 누락되었던 것을 반영.

- Dev/Topic_Programming(중첩 폴더, 78개)은 Dev 자체 최상위 폴더들
  (Architecture/Conventions/Engineering_Intelligence 등)과 완전 중복이라 제거.
- Dev 최상위 엔지니어링 지식 폴더(Architecture/Conventions/Engineering_Intelligence/
  Failure_Library/Generalized_Principles/Language/Pattern_Catalog/Platform_Guides/
  Subsystems, 77개)는 이미 Topic_Programming/Topic_Programming에 더 최신 버전이
  존재해 중복 제거(고유 콘텐츠 1개는 예외 처리하여 이동 보존).
- Dev의 W3Schools 언어 튜토리얼 폴더(Topic_C/CPP/CSS/CSharp/HOWTO/HTML/Java/
  JavaScript/PHP/Python/SQL/W3CSS, 1201개)는 전부 Topic_Programming 하위로 이동.
- 에이전트 운영 상태(.astra/docs)는 그대로 유지, 콘텐츠 폴더만 정리.
- Topic_Programming 최종 문서 수: 2784 → 3985.
2026-07-05 00:39:13 +09:00

5.7 KiB

id, title, category, status, verification_status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, created_at, updated_at, review_reason, merge_history, tags, raw_sources, applied_in, github_commit
id title category status verification_status canonical_id aliases duplicate_of source_trust_level confidence_score created_at updated_at review_reason merge_history tags raw_sources applied_in github_commit
cpp-iterators C++ Iterators Programming_Language draft conceptual
begin() end()
vector iterator
C++ 반복자
B 0.86 2026-07-04 2026-07-04
cpp
programming-language
w3schools
stl
iterator
https://www.w3schools.com/cpp/cpp_iterators.asp

CPP Iterators

🎯 한 줄 통찰 (One-line insight)

An iterator is a pointer with a container-agnostic interface — *it dereferences and ++it advances exactly like a raw C pointer walking an array, but the SAME begin()/end()/*it/++it syntax works identically across vector, list, deque, set, AND map, which is precisely the capability C's raw pointers never had (a int* walking an array shares no interface with a linked-list traversal via node->next) — and this uniform interface is why for-each loops and generic algorithms like sort()/find() can operate on any container without being rewritten per container type. [S1]

🧠 핵심 개념 (Core concepts)

  • Iterator = a "pointer" to an element — used to access/iterate through data structures by pointing to elements rather than copying them. [S1]
  • begin() / end() — functions belonging to the CONTAINER (not the iterator) that return an iterator to the first element / to one-past-the-last element; end() never points to a real element, only marks the stopping condition. [S1]
  • *it — dereference operator, accesses the value the iterator currently points to (and can assign through it: *it = "Tesla"; modifies the container in place). [S1]
  • ++it — advances the iterator to the next element. [S1]
  • auto keyword — lets the compiler infer the verbose iterator type (vector<string>::iterator) automatically; works in the loop declaration itself. [S1]
  • For-each vs. iterator — for-each is simpler for read-only traversal; iterators are required when you need to modify, erase, iterate in reverse, or skip elements during the loop. [S1]
  • .erase(it) inside a loop — removing an element mid-iteration returns the NEXT valid iterator, which is why the erase-loop pattern reassigns it = cars.erase(it); instead of also calling ++it. [S1]
  • rbegin() / rend() — reverse-order counterparts to begin()/end(), for iterating backward. [S1]
  • Iterator support is not universal — vector, list, deque, map, and set support iterators; stack and queue do NOT. [S1]
  • Iterators power <algorithm> functionssort(), find(), etc. take a begin/end iterator pair as parameters rather than the container itself. [S1]

📖 세부 내용 (Details)

  • Basic loop: vector<string>::iterator it; for (it = cars.begin(); it != cars.end(); ++it) { cout << *it; }. [S1]
  • auto shorthand: for (auto it = cars.begin(); it != cars.end(); ++it) { cout << *it; }. [S1]
  • Erase-during-iteration pattern: for (auto it = cars.begin(); it != cars.end(); ) { if (*it == "BMW") { it = cars.erase(it); } else { ++it; } } — no ++it in the header since erase already advances. [S1]
  • Reverse iteration: for (auto it = cars.rbegin(); it != cars.rend(); ++it) { cout << *it; }. [S1]
  • Map iteration needs ->first/->second (arrow, since it is a pointer-like object to a pair): for (auto it = people.begin(); it != people.end(); ++it) { cout << it->first << it->second; }. [S1]
  • sort(cars.begin(), cars.end()); from <algorithm> — the same begin/end pair used for manual loops is reused as the algorithm's range argument. [S1]

⚖️ 모순 및 업데이트 (Contradictions & updates)

  • C의 원시 포인터에는 없던 통일 인터페이스가 도입됨: C에서 배열은 포인터 산술(arr + i)로, 연결 리스트는 node->next로 순회 방식이 완전히 달랐지만, C++ iterator는 vector/list/deque/set/map 모두에서 동일한 begin()/end()/*it/++it 문법을 재사용한다는 점이 핵심 차이로 확인됨. [S1]
  • stack/queue는 iterator를 지원하지 않음: vector/list/deque/map/set과 달리, 접근 지점이 의도적으로 제한된 stack과 queue는 iterator 자체를 지원하지 않는다는 점이 명시적으로 확인됨. [S1]

🛠️ 적용 사례 (Applied in summary)

vector에서 특정 값("BMW")을 가진 요소를 순회 중에 삭제하는 예제가 iterator가 for-each보다 유리한 실전 사례로 원문에서 제시됨. [S1]

💻 코드 패턴 (Code patterns)

Iterator-based erase during traversal — impossible with a simple for-each (C++):

#include <vector>
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (auto it = cars.begin(); it != cars.end(); ) {
  if (*it == "BMW") {
    it = cars.erase(it);  // erase returns the next valid iterator
  } else {
    ++it;
  }
}

검증 상태 및 신뢰도

  • 상태: draft
  • 검증 단계: conceptual
  • 출처 신뢰도: B (W3Schools — widely used educational reference, not a primary standards body)
  • 신뢰 점수: 0.86
  • 중복 검사 결과: 신규 생성 (New discovery)

🔗 지식 그래프 (Knowledge Graph)

📚 출처 (Sources)

📝 변경 이력 (Change history)

  • 2026-07-04: Initial draft synthesized from the W3Schools "C++ Iterators" page (Astra wiki-curation, P-Reinforce v3.1 format).