
📢 (Key-Value)로 이루어진 Pair 들을 특정 순서를 가지고 저장하는 타입
C++ STL 내부에 Map이 존재해요!
#include <map>을 헤더에 추가하시고 사용하면 됩니다.
변수 선언 방법은 아래와 같아요.
map<자료형, 자료형> 변수명;
| 메소드 이름 | 역할 |
|---|---|
| begin, end | Map의 처음과 끝의 Iterator 반환 |
| empty | Map 내부가 비어있는지 여부를 반환 |
| size | Map의 크기를 반환 |
| [], at | Map의 특정 Key를 가진 데이터에 접근 |
| insert | Map에 데이터 추가 |
| erase | Map에서 데이터 제거 |
| clear | Map 내부 요소 전부 제거 |
| swap | Map끼리 내부 데이터 교환 |
| find | 특정 Key값을 가진 데이터를 반환 |
Map에 데이터를 Insert 하는 방법은 2가지예요.
아래는 위의 메소드를 적용한 예제예요.
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> newMap;
/*---------------Insert Method----------------------*/
newMap.insert(pair<string, int>("Apple", 1000));
newMap.insert(pair<string, int>("Grape", 4000));
newMap["Peach"] = 5000;
newMap["Banana"] = 2000;
// insert는 Key가 중복이 되면 에러를 발생
// []는 Key가 중복이 되면 값을 Update
/*--------------------------------------------------*/
/*---------------Find Method------------------------*/
cout << newMap.find("Banana")->second << endl;
cout << newMap.find("Peach")->first << endl;
/*--------------------------------------------------*/
/*---------------[], at Method----------------------*/
cout << newMap["Peach"] << endl;
cout << newMap.at("Banana") << endl;
/*--------------------------------------------------*/
/*---------------Size Method------------------------*/
cout << newMap.size() << endl;
/*--------------------------------------------------*/
/*---------------Begin, End Method------------------*/
for(auto iter = newMap.begin(); iter != newMap.end(); iter++) {
cout << iter->first << " ";
cout << iter->second << endl;
}
/*--------------------------------------------------*/
/*---------------Erase Method-----------------------*/
newMap.erase("Grape");
/*--------------------------------------------------*/
/*---------------Clear Method-----------------------*/
newMap.clear();
/*--------------------------------------------------*/
/*---------------Empty Method-----------------------*/
if(newMap.empty())
cout << "Map is empty!!" << endl;
else
cout << "Map is not empty!!!" << endl;
/*--------------------------------------------------*/
}