TreeMap은 이진 탐색트리로 구현되어있으며, Key-Value쌍을 key값을 기준으로 오름차순으로 정렬한다.
삽입, 삭제, 탐색의 속도는 O(logN)으로 HashMap보단 느리지만 순서가 유지된다는 장점이 있다.
#include<iostream>
using namespace std;
#include<map>
int main()
{
// 정의
map<int, char> m;
// 삽입
m.insert({5, 'b'});
m.insert({2, 'c'});
m.insert({1, 'a'});
// key값으로 value값 얻어내기 -> 'a' 출력
cout << m[1] << endl;
// 삭제
m.erase(2);
// 탐색
cout << (m.find(1))->first << endl; // key값 반환 -> 1
cout << (m.find(1))->second << endl; // value값 반환 -> 'a'
// 탐색 결과가 없는 경우 m.end() 반환
if(m.find(2) == m.end()){
cout << "not found" << endl;
}
// 오름차순 순회 -> (1,a), (5,b) 출력
map<int, char>::iterator it;
for(it=m.begin(); it!=m.end(); it++)
{
cout << '(' << it->first << ',' << it->second << ')' << endl;
}
return 0;
}