레슨 4 / 8·20분
STL 컨테이너와 알고리즘
STL(Standard Template Library) 개요
C++ 표준 템플릿 라이브러리(STL)는 컨테이너, 반복자, 알고리즘의 세 가지 핵심 구성요소로 이루어져 있습니다. 제네릭 프로그래밍을 기반으로 타입에 독립적인 자료구조와 알고리즘을 제공합니다.
vector — 동적 배열
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// vector 생성과 초기화
vector<int> nums = {5, 2, 8, 1, 9, 3};
// 요소 추가
nums.push_back(7);
nums.push_back(4);
// 크기와 용량
cout << "크기: " << nums.size() << endl;
cout << "용량: " << nums.capacity() << endl;
// 인덱스 접근
cout << "첫 번째: " << nums[0] << endl;
cout << "안전한 접근: " << nums.at(1) << endl;
// 범위 기반 for 루프
for (const auto& n : nums) {
cout << n << " ";
}
cout << endl;
// 정렬
sort(nums.begin(), nums.end());
// 결과: 1 2 3 4 5 7 8 9
// 요소 삭제
nums.erase(nums.begin() + 2); // 3번째 요소 삭제
nums.pop_back(); // 마지막 요소 삭제
return 0;
}map과 unordered_map — 연관 컨테이너
cpp
#include <iostream>
#include <map>
#include <unordered_map>
using namespace std;
int main() {
// map: 정렬된 키-값 쌍 (Red-Black Tree)
map<string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
scores["Charlie"] = 92;
// 삽입
scores.insert({"Diana", 88});
// 탐색
if (scores.find("Alice") != scores.end()) {
cout << "Alice: " << scores["Alice"] << endl;
}
// 순회 (키 기준 정렬됨)
for (const auto& [name, score] : scores) {
cout << name << ": " << score << endl;
}
// unordered_map: 해시 기반 (평균 O(1) 탐색)
unordered_map<string, int> fast_scores;
fast_scores["Alice"] = 95;
fast_scores["Bob"] = 87;
// 키 존재 여부 확인
cout << "Alice 존재: " << fast_scores.count("Alice") << endl;
return 0;
}STL 알고리즘
cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
// 정렬
sort(v.begin(), v.end());
// 이진 탐색 (정렬된 상태에서)
bool found = binary_search(v.begin(), v.end(), 5);
cout << "5 존재: " << (found ? "Yes" : "No") << endl;
// 최솟값/최댓값
auto minIt = min_element(v.begin(), v.end());
auto maxIt = max_element(v.begin(), v.end());
cout << "최소: " << *minIt << ", 최대: " << *maxIt << endl;
// 합계
int sum = accumulate(v.begin(), v.end(), 0);
cout << "합계: " << sum << endl;
// 조건에 맞는 요소 개수
int cnt = count_if(v.begin(), v.end(),
[](int x) { return x > 3; });
cout << "3보다 큰 요소 수: " << cnt << endl;
// 변환 (각 요소 2배)
vector<int> doubled(v.size());
transform(v.begin(), v.end(), doubled.begin(),
[](int x) { return x * 2; });
return 0;
}- •
vector— 동적 배열, 끝에 삽입/삭제 O(1) - •
map— 정렬된 키-값 쌍 (Red-Black Tree), O(log n) - •
unordered_map— 해시 기반, 평균 O(1) 탐색 - •
set/unordered_set— 중복 없는 집합 - •
deque— 양쪽 끝 삽입/삭제 O(1) - •
stack,queue,priority_queue— 어댑터 컨테이너
💡
vector는 가장 많이 사용되는 STL 컨테이너입니다. 특별한 이유가 없다면 배열 대신 vector를 사용하세요. reserve()로 미리 메모리를 확보하면 재할당을 줄일 수 있습니다.