[C++] Map

date:

Updated:


Categories:

Tags: , ,


Map

#include <map>

empty container constructors

map<key_type, value_type> first;
first['a']=10;
first['b']=30;
first['c']=50;
first['d']=70;

가장 많이 쓰는 constructor 형태이다. map의 key는 중복을 허용하지 않는다.

range constructor

map<key_type, value_type> second(first.begin(), first.end());
# a,b,c,d

map<key_type, value_type> second(first.begin(), first.find('c'));
# a,b

map<key_type, value_type> second(first.find('b'), first.lower_bound('d'));
# b,c

map<key_type, value_type> second(first.find('b'), first.upper_bound('c'));
# b,c

여러가지 iterator 관련 member function으로 위와 같이 특정 범위만 copy하여 range constructor를 구성할 수 있다.

insert vs emplace

first.insert(make_pair<key_type, value_type>('e', 5));

first.emplace('e', 5);

insert : insert element
emplace : Construct and insert elements

insert 보다는 emplace가 편하다.

map에서 중요한 점은 key의 오름차순으로 정렬되어 있다는 것이다. 이는 binary search tree중 Red Black Tree로 구현되어 있다는 점 때문인데, 이러한 특성 때문에 unordered_map보다 access 속도가 느리다.

만약 내림차순으로 정렬하려면, 다음과 같이 작성하면 된다.

map<key_type, value_type, greater<key_type> > first;

Leave a comment