---
id: cpp-sets
title: "C++ Sets"
category: "Programming_Language"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["std::set", "unique sorted elements C++", "C++ 셋"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.86
created_at: 2026-07-04
updated_at: 2026-07-04
review_reason: ""
merge_history: []
tags: ["cpp", "programming-language", "w3schools", "stl", "set"]
raw_sources: ["https://www.w3schools.com/cpp/cpp_sets.asp"]
applied_in: []
github_commit: ""
---

# [[CPP Sets]]

## 🎯 한 줄 통찰 (One-line insight)
`set` is the first STL container in this series where insertion ORDER is thrown away entirely — every container so far (vector/list/stack/queue/deque) preserved the order elements were added in, but a set auto-sorts on every insert AND silently drops duplicates, meaning `cars.insert("BMW")` twice is not an error, not a no-op that keeps the old value, but simply invisible — the second insert vanishes with no feedback, which is the opposite of the C mentality where writing the same array slot twice always visibly overwrites it. [S1]

## 🧠 핵심 개념 (Core concepts)
- **Automatic ascending sort** — elements are always kept in sorted order (alphabetical for strings, numeric for ints), regardless of insertion order. [S1]
- **Uniqueness enforced silently** — inserting a duplicate value is simply ignored; no error, no exception, no indication. [S1]
- **No index access, no in-place value change** — since order is determined by sorting rather than position, elements cannot be retrieved by `[i]`, and an existing element's VALUE cannot be modified (only added via `.insert()` or removed via `.erase()`). [S1]
- **`greater<type>` functor** — passed as a second template parameter (`set<int, greater<int>> numbers`) to reverse the default ascending sort to descending. [S1]
- **`.insert()` / `.erase()` / `.clear()`** — add one element / remove one specific element / remove everything. [S1]
- **`.size()` / `.empty()`** — same semantics as other containers. [S1]
- **Looping** — for-each only (like list); no indexed loop since there's no index. [S1]

## 📖 세부 내용 (Details)
- Declaration + auto-sort: `set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};` prints in alphabetical order (BMW, Ford, Mazda, Volvo), NOT insertion order. [S1]
- Numeric sets sort numerically: `set<int> numbers = {1, 7, 3, 2, 5, 9};` prints 1,2,3,5,7,9. [S1]
- Descending order: `set<int, greater<int>> numbers = {1, 7, 3, 2, 5, 9};` prints 9,7,5,3,2,1. [S1]
- Duplicate handling demonstrated directly: `set<string> cars = {"Volvo", "BMW", "Ford", "BMW", "Mazda"};` still prints only 4 unique elements. [S1]
- Add/remove: `cars.insert("Tesla");` / `cars.erase("Volvo");` / `cars.clear();`. [S1]

## ⚖️ 모순 및 업데이트 (Contradictions & updates)
- **삽입 순서가 완전히 무시됨**: 지금까지의 모든 컨테이너(vector/list/stack/queue/deque)는 삽입 순서를 유지했지만, set은 매번 자동으로 정렬 순서를 재적용하여 삽입 순서 자체가 의미를 잃는다는 점이 이번 챕터에서 확인됨. [S1]
- **중복 삽입이 조용히 무시됨**: C 배열에서 같은 인덱스에 값을 두 번 쓰면 항상 눈에 띄게 덮어써지지만, set에 같은 값을 두 번 insert()하면 아무 에러도 피드백도 없이 두 번째 삽입이 그냥 사라진다는 점이 확인됨. [S1]

## 🛠️ 적용 사례 (Applied in summary)
현재 발견된 실제 적용 사례가 없습니다 — 자동차 이름 set에 중복값을 넣어 자동으로 걸러지는 것을 보여주는 예제가 원문에서 제시됨. [S1]

## 💻 코드 패턴 (Code patterns)
A set auto-sorts and silently drops duplicates on insert (C++):
```cpp
#include <set>
set<string> cars = {"Volvo", "BMW", "Ford", "BMW", "Mazda"};
// Output (sorted, deduplicated): BMW, Ford, Mazda, Volvo

set<int, greater<int>> numbers = {1, 7, 3, 2, 5, 9};
// Descending via greater<type>: 9, 7, 5, 3, 2, 1

cars.insert("Tesla");
cars.erase("Volvo");
```

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

## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[C++ Tutorial]]
- **관련 개념:** [[CPP Deque]], [[CPP Maps]], [[CPP Iterators]]
- **참조 맥락:** 데이터 구조(STL) 섹션 — Maps 챕터로 이어짐.

## 📚 출처 (Sources)
- [S1] W3Schools — C++ Sets — https://www.w3schools.com/cpp/cpp_sets.asp

## 📝 변경 이력 (Change history)
- 2026-07-04: Initial draft synthesized from the W3Schools "C++ Sets" page (Astra wiki-curation, P-Reinforce v3.1 format).
