예시
#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이란?
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
반응형
'Algorithm' 카테고리의 다른 글
소수값 구하기 - 에라토스테네스의 체 (1) | 2023.12.04 |
---|---|
동적 계획법, DP(Dynamic Programming) c++ (0) | 2023.04.14 |
BFS(너비 우선 탐색) 알고리즘 (0) | 2022.07.06 |
DFS(깊이 우선 탐색) 알고리즘 (0) | 2022.07.04 |
투포인터 알고리즘(Two Pointers Algorithm) - c++ (0) | 2022.07.01 |