Program Language/C++
(STL) map 사용법
ji.o.n.e
2020. 8. 3. 10:27
1. 기본 형태
- map<key, value> : key와 value를 pair 형태로 선언
2. map의 주요 멤버들
- begin(): 첫 번째 원소의 iterator를 반환
- end() : 마지막 원소의 iterator를 반환
- insert(make_pair(key, value)) : map에 원소를 pair 형태로 추가
- erase(key) : map에서 key(키값)에 해당하는 원소 삭제
- clear() : map의 모든 원소들 삭제
- find(key) : key에 해당하는 iterator를 반환
- count(key) : key에 해당하는 원소(value) 의 개수를 반환
- size() : map 원소들의 수를 반환
- empty() : map이 비어있으면 true 그렇지 않으면 false 반환
3. 특징
- 검색을 자주 할 때 사용
- 그러나 항상 정렬되어있어야하기 때문에 삽입, 삭제를 자주하면 안됨
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
map<string, int> mp;
mp.insert({"a",1});
mp.insert({"c",2});
mp.insert({"b",3});
mp.insert({"e",4});
mp.insert({"d",5});
mp.erase("c");
cout<<"map size : "<<mp.size()<<'\n'; //map size : 4
for (auto it = mp.begin(); it != mp.end(); it++)
{
cout << "key : " << it->first << " value: " << it->second << '\n';
}
//key : a value: 1
//key : b value: 3
//key : d value: 5
//key : e value: 4 -> 정렬되어있음
return 0;
}