[c++] key-value형을 사용할 수 있는 std::unordered_map

숭글·2023년 1월 12일
0

unordered_map

#include <unordered_map>

key-value형태로 값을 저장하는 컨테이너이다.

template < class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator< pair<const Key,T> > class unordered_map;
  • key값을 이용해 element를 식별하기때문에 key값은 유니크해야한다.
  • key와 element의 타입은 달라도 된다.
  • map과 달리 정렬돼있지 않지만, 해쉬 테이블을 이용해 key에 빠르게 접근할 수 있다. (해쉬 값에 따라 buckek으로 정리돼있다.)
  • key를 찾아 접근하는 건 map보다 빠르지만, range iteration으로 접근하는 건 비효율적이다.
  • allocator object를 사용하여 storage를 동적으로 관리한다.
  • direct access operator(operator[])를 이용해 원소에 접근할 수 있다.

Template parameters

  • Key
    : key의 타입 (= unordered_map::key_type)

  • T
    : value의 타입 (= unordered_map::mapped_type) (=/= unordered_map::value_type)

  • Hash
    : size_t타입의 고유한 값을 리턴할 해쉬 값 (= unordered_map::hasher)
    , hash가 기본값이다.

  • Pred
    : key값을 비교할 binary predicate이다.(= unordered_map::key_equal)

  • Alloc
    : allocator object의 타입.
    기본값은 가장 단순한 memory allocation model을 정의하고 값에 독립적인 allocator class template를 사용한다.(= unordered_map::allocator_type)

(unordered_map::value_type은 key와 value의 pair을 정의한 것이다.)

typedef pair<const Key, T> value_type;

iterator 사용

  • unordered_map의 iterator는 value_type에 접근한다.(key와 value 값을 둘 다 가지고있다.)
    unordered_map<Key,T>::iterator it;
    (*it).first; 	 // = it->first;  
    (*it).second; 	 // = it->second;
    (*it);     // the "element value" (of type pair<const Key,T>) 
    

Member functions

Element lookup

  • find
    iterator find ( const key_type& k );const_iterator find ( const key_type& k ) const;
    • return value
      : 찾는 key값이 존재하면 해당하는 key값의 element 반환,
      없다면 unordered_map::end을 반환.
  • count
    size_type count ( const key_type& k ) const;
    • return value
      : 찾는 key 값이 존재라면 1을 반환,
      없으면 0을 반환.

Modifiers

  • ✨ emplace
    : construct and insert element
    template <class... Args>pair<iterator, bool> emplace ( Args&&... args );
    key가 이미 존재하는 경우가 아니면 insert한다.
    , 이미 존재하는 object를 복사하거나 옮겨주는 insert()라는 비슷한 멤버 함수가 존재한다.
    • return value
      : pair object를 반환한다.
      삽입이 성공한 경우엔 first component에 삽입된 element의 iterator, second component에 true값이 들어있다. 다른 경우엔 first component에 삽입된 container내부에 이미 존재하던 key값의 element, second component에 false값이 들어있다.

example >>

#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
std::unordered_map<std::string,std::string> mymap;

mymap.emplace ("NCC-1701", "J.T. Kirk");
mymap.emplace ("NCC-1701-D", "J.L. Picard");
mymap.emplace ("NCC-74656", "K. Janeway");

std::cout << "mymap contains:" << std::endl;
for (auto& x: mymap)
  std::cout << x.first << ": " << x.second << std::endl;

std::cout << std::endl;
return 0;
}  

// output >>
// mymap contains:
// NCC-1701: J.T. Kirk
// NCC-1701-D: J.L. Picard
// NCC-74656: K. Janeway
  • insert
    pair<iterator,bool> insert ( const value_type& val );
    새로운 element를 추가한다.
    key가 존재하지 않는 경우에만 추가한다.
    (버전이 너무 많아서 직접 확인하는 게 편할 것 같다..)

📖 std::unordered_map
📖 std::unordered_map::find
📖 std::unordered_map::count
📖 std::unordered_map::insert
📖 std::unordered_map::emplace

profile
Hi!😁 I'm Soongle. Welcome to my Velog!!!

0개의 댓글