Files
2nd/10_Wiki/Dev/Topic_CPP/CPP_Iterators.md
T
Antigravity Agent 1cfd3bbb56 docs(10_Wiki): 위키 구조 정리 — 언어 튜토리얼 카테고리 폴더 제거 + 신규 자산 동기화
Topic_CSS/Topic_HTML/Topic_JavaScript/Topic_Prompt/Topic_Comfyui 등 기존 카테고리 폴더를 정리하고,
Topic_Graphic/Dev 등 신규 산출물과 Topics 내부 세션/메모리 기록을 동기화.
2026-07-05 00:10:59 +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).