💡 퀵 접속: cpp.kr/map
C++ 표준 라이브러리의 연관 컨테이너로, 키-값 쌍을 저장하고 관리하는 컨테이너입니다.
#include <iostream>
#include <map>
#include <string>
int main() {
// 맵 생성
std::map<std::string, int> scores;
// 요소 추가
scores["Alice"] = 95;
scores["Bob"] = 87;
scores["Charlie"] = 92;
// 요소 접근
std::cout << "Alice의 점수: " << scores["Alice"] << std::endl;
// 요소 존재 여부 확인
if (scores.find("David") != scores.end()) {
std::cout << "David의 점수: " << scores["David"] << std::endl;
} else {
std::cout << "David의 점수는 없습니다." << std::endl;
}
return 0;
}
실행 결과:
Alice의 점수: 95 David의 점수는 없습니다.
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> scores = {
{"Alice", 95},
{"Bob", 87},
{"Charlie", 92}
};
// 반복자로 순회
std::cout << "반복자로 순회:" << std::endl;
for (auto it = scores.begin(); it != scores.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
// 범위 기반 for문
std::cout << "\n범위 기반 for문:" << std::endl;
for (const auto& pair : scores) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
실행 결과:
반복자로 순회: Alice: 95 Bob: 87 Charlie: 92 범위 기반 for문: Alice: 95 Bob: 87 Charlie: 92
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> scores = {
{"Alice", 95},
{"Bob", 87},
{"Charlie", 92}
};
// 요소 삽입
scores.insert({"David", 88});
// 요소 수정
scores["Bob"] = 90;
// 요소 삭제
scores.erase("Charlie");
// 맵 출력
std::cout << "조작 후 맵:" << std::endl;
for (const auto& pair : scores) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
실행 결과:
조작 후 맵: Alice: 95 Bob: 90 David: 88
| 메서드 | 설명 |
|---|---|
| insert() | 요소 삽입 |
| erase() | 요소 삭제 |
| find() | 요소 검색 |
| count() | 키의 개수 반환 |
| size() | 요소 개수 반환 |
| empty() | 맵이 비어있는지 확인 |
| clear() | 모든 요소 삭제 |
| begin() | 시작 반복자 |
| end() | 끝 반복자 |