(Unordered_)Map

nana·2025년 3월 5일

c++ 정리

목록 보기
6/6

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

unordered_map VS map 비교

  • unordered_map은 정렬이 필요 없고, 빠른 탐색이 필요한 경우 유리
  • map은 Key 기준 정렬이 필요할 때 유리

선언 및 초기화

#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 형태로 데이터 저장

주요 함수

삽입 (insert)

myMap.insert({"orange", 150});

or 아래의 경우는 존재하는 Key에 값을 덮어씀.

myMap["orange"] = 150;

검색 (find)

auto it = myMap.find("banana");
if (it != myMap.end()) {
    cout << "Found: " << it->second << endl;
} else {
    cout << "Not found" << endl;
}

find()는 Key가 있으면 iterator 반환, 없으면 end() 반환

Key 존재 여부 (count)

if (myMap.count("apple")) {
    cout << "apple exists!" << endl;
}

count()는 Key가 존재하면 1 반환, 없으면 0 반환

삭제 (erase)

myMap.erase("banana");

해당 Key 제거

모든 원소 순회(for문 사용)

for (const auto &[key, value] : myMap) {
    cout << key << ": " << value << endl;
}

순서 보장 없음

unordered_map 사용 시 주의할 점

  • Key의 순서가 일정하지 않다!!!
unordered_map<string, int> myMap = {{"b", 2}, {"a", 1}, {"c", 3}};
for (const auto &[key, value] : myMap) {
    cout << key << ": " << value << endl;
}

const auto & 꼭 넣어야할까?

필수는 아니지만 넣는 것이 효율적

for (pair<string, int> genrePair : sortedDic) { }
for (const pair<string, int> &genrePair : sortedDic) { }
for (auto genrePair : sortedDic) { }
for (const auto &genrePair : sortedDic) { }

c++에서는 _를 변수명으로 사용할 수 있음!

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

0개의 댓글