Map 순회하기
1. iterator 을 이용한 순회
// iterator를 사용하여 순회
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
2. 범위 기반 순회
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
}
Map의 내부 (Key, Value)는 pair 형태로 꺼낼 수 있다.
요소 검색하기
map은 find 를 이용해서 Key 값이 있는 지 검색할 수 있다.
auto it = myMap.find(key);
if (it != myMap.end()) {
std::cout << "Key found. Value: " << it->second << std::endl;
} else {
std::cout << "Key not found." << std::endl;
}
Map 내림차순 정렬하기
map은 균형 이진 트리 자료구조로 구현되었기 때문에, 기본적으로 오름차순 정렬로 저장된다.
내림차순 정렬로 저장하기 위해서는 비교자를 이용해 map을 선언하면 된다.
#include <iostream>
#include <map>
// 내림차순 비교 함수 정의
struct Compare {
bool operator()(const int& a, const int& b) const {
return a > b;
}
};
int main() {
std::map<int, std::string, Compare> myMap;
}
'Langauge > C++' 카테고리의 다른 글
[BOJ/C++] 백준 12869 - 뮤탈리스크 (0) | 2023.07.27 |
---|---|
[BOJ/C++] 백준 1495 - 기타리스트 (0) | 2023.07.27 |
[C++] 스택(stack), 큐(queue), 데크(deque) 직접 구현하기 (1) | 2023.06.19 |
[C++] 이분 탐색으로 lower_bound, upper_bound 구현하기 (0) | 2023.06.19 |
[C++] 코딩테스트에 자주 나오는 문자열 처리 예제들 (0) | 2023.06.19 |