#include <map>
1. 기본형
- map<key,value> : key와 value를 pair 형태로 선언, 각 key와 value에 사용할 type 선언
2. 반복자(iterator)
- begin() : beginning iterator를 반환
- end() : end iterator를 반환
3. 추가 / 삭제
- insert(make_pair(key,value)) : 맵에 원소를 pair 형태로 추가
- erase(key) : 맵에서 key(키값)에 해당하는 원소 삭제
- clear() : 맵의 원소들 모두 삭제
4. 조회
- find(key) : key(키값)에 해당하는 iterator 반환, iterator의 first, second 통해 key, value에 접근 -> 없으면 end() 반환
- count(key) : key(키값)에 해당하는 원소들(value들)의 개수를 반환
5. 기타
- empty() : 맵이 비어있으면 true 아니면 false를 반환
- size() : 맵 원소들의 수를 반환
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
// 기본형 선언
map<string, int> m;
// iterator 선언
map<string, int>::iterator it;
// insert(key,value)
m.insert(make_pair("a", 1));
m.insert(make_pair("b", 2));
m.insert(make_pair("c", 3));
m.insert({"d", 4});
m.insert({"e", 5});
// 주로 사용하는 형태
m["f"] = 6;
// erase(key)
m.erase("d");
m.erase("e");
m.erase(m.find("f"));
// empty(), size()
if(!m.empty()) cout << "m size : " << m.size() << "\n";
// find(key)
cout << "a : " << m.find("a")->second << "\n";
cout << "b : " << m.find("b")->second << "\n";
// it = m.find("a");
// cout << "a : " << (*it).second << "\n";
// if(m.find("a") != m.end())을 통해 키값 유무 확인
// count(key)
cout << "a count : " << m.count("a") << "\n";
cout << "b count : " << m.count("b") << "\n";
// if(m.count("a") != 0)을 통해 키값 유무 확인
// begin(), end()
cout << "traverse" << "\n";
// for(auto it = m.begin(); it != m.end(); it++)
for(it = m.begin(); it != m.end(); it++)
{
cout << "key : " << it->first << " " << "value : " << it->second << "\n";
}
return 0;
}
|
cs |
출처 :
https://twpower.github.io/91-how-to-use-map-in-cpp
'STL > map' 카테고리의 다른 글
<map> vs <unordered_map> 차이 (0) | 2020.03.31 |
---|