Algorithm

hash map - C++ STL

_yh47 2023. 3. 28. 14:00

예시

#include<iostream>
#include<unordered_map>

int main()
{
    std::unordered_map<std::string, std::string> hashmap;
    
    //insert
    hashmap.insert({"key1","value1"});
	hashmap.insert({"key2","value2"});
    hashmap.insert({"key3","value3"});
    
    //find
    std::cout << hashmap.find("key2")->first << ' ' << hashmap.find("key2")->second << std::endl;
    
    std::cout << std::endl;
    
   
    for(auto map : hashmap)
    {
    	std::cout << map.first << ' ' << map.second << std::endl;
    }
    
}

 

결과


Hash map이란?

https://www.geeksforgeeks.org/unordered_map-in-cpp-stl/

key값을 사용하여 value값을 검색할 수 있는 key-value 쌍을 포함하는 중요한 데이터 구조입니다.

 

값을 찾는데 O(1) 시간이 걸려 시간면에서는 좋은 성능을 보여주지만, 해시충돌이 일어난다면 탐색 성능이 안좋아집니다.

따라서 Hash map이 가장 좋다고는 할 수 없습니다.

 

 

unordered_map< > 안에 int, string, char, float 등 다양한 데이터 타입이 들어갈 수 있습니다.

insert 같은 경우는 한 가지 방법만 있는 것이 아닙니다.

 

  hashmap.insert(make_pair("key1","value1"));
  //또는
  hashmap["key1"]="value1";
  //또는
  hashmap.insert({"key1","value1"});

모두 같은 기능을 가지고 있습니다.

 

 

더 알아보고싶은 함수가 있다면 공식문서를 통해 찾아보는 것을 추천드립니다.

 

https://learn.microsoft.com/en-us/cpp/standard-library/unordered-map-class?view=msvc-170 

 

unordered_map Class

API reference for the C++ Standard Library container class `unordered_map`, which controls a varying-length sequence of elements.

learn.microsoft.com

 

 

반응형