Files
2nd/10_Wiki/Dev/Topic_CPP/CPP_Maps.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.2 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-maps C++ Maps Programming_Language draft conceptual
std::map
key-value pairs C++
C++ 맵
B 0.86 2026-07-04 2026-07-04
cpp
programming-language
w3schools
stl
map
https://www.w3schools.com/cpp/cpp_maps.asp

CPP Maps

🎯 한 줄 통찰 (One-line insight)

map reuses set's "auto-sort + unique" behavior but shifts what must be unique from the ELEMENT itself to just the KEY, letting VALUES repeat freely — and it overloads [] with a dual meaning no other container has: people["Jenny"] = 22; on a key that doesn't exist SILENTLY CREATES it (unlike vector's [], which never grows the container), meaning map's [] is simultaneously a read, a write, AND an insert operator depending on context, a three-way overload that requires .at() or .count() when you need to tell those cases apart. [S1]

🧠 핵심 개념 (Core concepts)

  • map<keytype, valuetype> name — two type parameters instead of one, e.g. map<string, int> people;; requires <map>. [S1]
  • Unique keys, non-unique values — like set's uniqueness rule but applied only to the key half of each pair; values can repeat freely. [S1]
  • Auto-sorted by key — same ascending-order-by-default behavior as set, reversible with greater<type> as the third template parameter. [S1]
  • [] as read/write/insertpeople["John"] reads the value for an existing key, people["John"] = 50; overwrites it, and people["Jenny"] = 22; on a NEW key silently inserts it — three distinct behaviors under one syntax. [S1]
  • .at() — safer read/write alternative that throws if the key doesn't exist, unlike [] which would silently create a new entry instead of erroring. [S1]
  • .insert({key, value}) — explicit alternative to [] for adding; if the key already exists, the insert is silently ignored (first value wins, matching set's duplicate-drop behavior). [S1]
  • .count(key) — returns 1/0 to check key existence without risking an accidental insert. [S1]
  • Looping requires auto + .first/.secondfor (auto person : people) { cout << person.first << person.second; }, since each element is a key-value pair, not a single value. [S1]

📖 세부 내용 (Details)

  • Declaration: map<string, int> people = { {"John", 32}, {"Adele", 45}, {"Bo", 29} };. [S1]
  • Access: people["John"], people.at("Adele"); .at() throws for a missing key (people.at("Jenny") errors), while people["Jenny"] would just create it. [S1]
  • Duplicate-key insert is ignored: people.insert({"Jenny", 22}); people.insert({"Jenny", 30}); keeps only 22. [S1]
  • Existence check without mutation: people.count("John") returns 1. [S1]
  • Loop pattern: for (auto person : people) { cout << person.first << " is: " << person.second << "\n"; } — output is sorted by key (Adele, Bo, John), not insertion order. [S1]

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

  • [] 연산자가 vector와 다르게 동작함: vector의 []는 존재하는 인덱스만 읽고 범위를 벗어나면 정의되지 않은 동작이었지만, map의 []는 존재하지 않는 키에 값을 대입하면 조용히 새 요소를 생성한다는 점이 vector와의 핵심 차이로 확인됨. [S1]
  • set의 고유성 규칙이 키에만 적용되도록 완화됨: set은 요소 전체가 고유해야 했지만, map은 키만 고유하면 되고 값은 자유롭게 중복될 수 있다는 점이 set 규칙의 부분적 완화로 확인됨. [S1]

🛠️ 적용 사례 (Applied in summary)

사람 이름과 나이를 저장하는 map에서 값을 읽고, 수정하고, .count()로 존재 여부를 확인하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]

💻 코드 패턴 (Code patterns)

Map's [] reads, writes, AND silently inserts depending on context (C++):

#include <map>
map<string, int> people = { {"John", 32}, {"Adele", 45}, {"Bo", 29} };

people["Jenny"] = 22;          // key doesn't exist -> silently inserted
cout << people.at("Adele");    // safe read, throws if missing
cout << people.count("John");  // 1 if exists, 0 if not -- no risk of insert

for (auto person : people) {   // sorted by key: Adele, Bo, Jenny, John
  cout << person.first << " is: " << person.second << "\n";
}

검증 상태 및 신뢰도

  • 상태: 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++ Maps" page (Astra wiki-curation, P-Reinforce v3.1 format).