본문 바로가기
C#/[루키스] 자료구조

[C# 섹션 5] Dictionary

by 묻공러 2025. 6. 23.

# Dictionary

- C#의 Dictionary와 HashSet

C#의 Dictionary는 C++의 unordered_map과 거의 같다

C#의 HashSet은 C++의 unordered_set과 거의 같다

 

- 주의점

두 언어 모두 임의접근을 하는 경우 주의할 필요가 있다

C#의 Dictionary[key]는 키가 없으면 예외가 발생한다

반면, C++의 unordered_map[key]는 키가 없으면 기본 값을 생성하여 추가된다

// C#
Dictionary<int, string> dict = new Dictionary<int, string>();
var value = dict[1]; // KeyNotFoundException 발생
// C++
unordered_map<int, string> dict;
auto value = dict[1]; // 새로운 키 1이 생성되고, 값은 기본값("")이 들어감

 

- 주의점 해결법

C#은 키가 존재하는지 확인하고 가져오도록 TryGetValue를 사용하면 된다

C++은 find로 해당 값을 확인하고 가져오면 된다

// C#
Dictionary<int, string> dict = new Dictionary<int, string>();
var value = dict[1]; // KeyNotFoundException 발생

// 해결법
var result;
bool found = dict.TryGetValue(1, out result);
// C++
unordered_map<int, string> dict;
auto value = dict[1]; // 새로운 키 1이 생성되고, 값은 기본값("")이 들어감

// 해결법
if (dict.find(1) != dict.end()) 
{
    auto value = dict[1];
}

 

- Dictionary 사용법

using System;
using System.Collections.Generic;

class Monster
{
    public int id;

    public Monster(int id)
    {
        this.id = id;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<int, Monster> dic = new Dictionary<int, Monster>();

        // 값 추가
        dic.Add(1, new Monster(1));
        dic[5] = new Monster(5);

        // 대량 추가
        for (int i = 0; i < 10000; i++)
        {
            dic.Add(i, new Monster(i));
        }

        // 잘못된 접근 (키가 없어서 예외 발생)
        // Monster mon = dic[20000]; // KeyNotFoundException 발생

        // 안전한 접근
        Monster mon2;
        bool found = dic.TryGetValue(7777, out mon2);
        if (found)
        {
            Console.WriteLine($"Monster {mon2.id} 찾음!");
        }
        else
        {
            Console.WriteLine("Monster를 찾을 수 없음.");
        }

        // 삭제 및 전체 삭제
        dic.Remove(7777);
        dic.Clear();
    }
}

'C# > [루키스] 자료구조' 카테고리의 다른 글

[C# 섹션 5] List  (2) 2025.06.23
[C# 섹션 5] 배열  (0) 2025.06.22