본문 바로가기

SW 지식/C 와 C++ 공부

[C++] unordered_map 컨테이너

unordered_map 은 C++ STL 중 하나로, map보다 더 빠른 탐색을 위해 성능이 개선된 자료구조입니다.

Unordered maps are associative containers that store elements formed by the combination of
a key value and a mapped value, and which allows for fast retrieval of individual elements based on their keys.
Unordered map is an associative container that contains key-value pairs with unique keys. Search, insertion, and removal of elements have average constant-time complexity.

std::map은 자동으로 정렬이 필요할 때 사용되는데  탐색(Search), 삽입(Insertion), 제거(Removal)가 빈번할 때 성능이 현저히 떨어집니다. 그래서 이를 개선하기 위해 C++11 부터 std::unordered_map 이 추가되었습니다.

std::unordered_map은,  std::map처럼 key value와 mapped value를 쌍으로 저장하고 있는 컨테이너입니다. 이때, key value는 중복을 허용하지 않습니다.


사용 예시를 한번 살펴보겠습니다.

unordered_map<Key,T>::iterator it;
(*it).first;             // the key value (of type Key)
(*it).second;            // the mapped value (of type T)
(*it);                   // the "element value" (of type pair<const Key,T>) 

it->first;               // same as (*it).first   (the key value)
it->second;              // same as (*it).second  (the mapped value)

unordered_map 컨테이너의 iterator는 value의 요소를 가리킵니다. 그래서 위와 같이 iterator를 사용하여 key value와 mapped value를 각각 `first`와 `second`를 사용하여 접근할 수 있습니다.

 

std::unordered_map에는 map처럼 다양한 함수가 있는데 자세한 것은 아래 페이지를 참고해주세요~

(개인적으로 필요한) emplace() 함수에 대해 다음 페이지에서 더 자세히 알아보겠습니다.

참조 1) https://www.cplusplus.com/reference/unordered_map/unordered_map/

참조 2) https://en.cppreference.com/w/cpp/container/unordered_map

'SW 지식 > C 와 C++ 공부' 카테고리의 다른 글

[C++] std::pair와 std::tuple [TBD]  (0) 2021.10.01
[C++] emplace 함수  (0) 2021.09.23
[C++] std::function 은 무엇일까  (0) 2021.09.16
[C++] 람다 식 Lambda expressions  (0) 2021.09.16
[C++] mutable 변수  (0) 2021.09.03