c++의 해시 기반 컨테이너, Key-Value 형태의 데이터를 빠르게 검색/삽입/삭제 가능한 자료구조

#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> myMap;
// 데이터 추가
myMap["apple"] = 100;
myMap["banana"] = 200;
myMap["cherry"] = 300;
// 값 출력
cout << "apple: " << myMap["apple"] << endl;
// 출력 apple: 100
return 0;
}
Key-Value 형태로 데이터 저장
myMap.insert({"orange", 150});
or 아래의 경우는 존재하는 Key에 값을 덮어씀.
myMap["orange"] = 150;
auto it = myMap.find("banana");
if (it != myMap.end()) {
cout << "Found: " << it->second << endl;
} else {
cout << "Not found" << endl;
}
find()는 Key가 있으면 iterator 반환, 없으면 end() 반환
if (myMap.count("apple")) {
cout << "apple exists!" << endl;
}
count()는 Key가 존재하면 1 반환, 없으면 0 반환
myMap.erase("banana");
해당 Key 제거
for (const auto &[key, value] : myMap) {
cout << key << ": " << value << endl;
}
순서 보장 없음
unordered_map<string, int> myMap = {{"b", 2}, {"a", 1}, {"c", 3}};
for (const auto &[key, value] : myMap) {
cout << key << ": " << value << endl;
}
필수는 아니지만 넣는 것이 효율적
for (pair<string, int> genrePair : sortedDic) { }
for (const pair<string, int> &genrePair : sortedDic) { }
for (auto genrePair : sortedDic) { }
for (const auto &genrePair : sortedDic) { }

근데 뭐 가능하긴하나 비추라고 함.