C# 자료구조 맛보기

POSI·2022년 12월 2일
0

C#

목록 보기
6/6

해당 문서는 인프런 [C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part1: C# 기초 프로그래밍 입문을 듣고 정리한 필기 노트입니다.

배열 (참조 타입)

초기화

int[] scores = new int[5];
int[] scores = new int[5] { 10, 20, 30, 40, 50 };
int[] scores = new int[] { 10, 20, 30, 40, 50 };

배열 길이

int length = scores.Length;

배열 하나씩 접근

// 방법 1
for (int i = 0; i < scores.Length; i++)
{
	Console.WriteLine(scores[i]);
}
        
// 방법 2
foreach (int score in scores)
{
	Console.WriteLine(scores);
}
	

다차원 배열

int[] arr = new int[2, 3];
    
// 2F [ . . . ]
// 1F [ . . . ]

맵 예시

class Map
{
	int[,] tiles = {
	{ 1, 1, 1, 1, 1 },
	{ 1, 0, 0, 0, 1 },
	{ 1, 0, 0, 0, 1 },
	{ 1, 0, 0, 0, 1 },
	{ 1, 1, 1, 1, 1 }
};
        
public void Render()
{
	var defaultColor = Console.ForegroundColor;
        
	for (int y = 0; y < tiles.GetLength(0); y++)
	{
	for (int x = 0; x < tiles.GetLength(1); x++)
	{
  	if (tiles[y, x] == 1)
		Console.ForegroundColor = ConsoleColor.Red;
	else
		Console.ForegroundColor = ConsoleColor.Green;
	Console.Write('|u25cf')
	}
	Console.WriteLine();
}
        
	Console.ForegroundColor = defaultColor;
}

가변 배열

int[][] a = new int[3][];
a[0] = new int[3];
a[1] = new int[6];
a[2] = new int[2];
    
// [ . . ]
// [ . . . . . . ]
// [ . . . ]
    

List (동적 배열)

using System.Collections.Generic;
    
List<int> list = new List<int>(); // <> 안에 type 넣기
// 초기화
for (int i = 0; i < 5; i++)
	list.Add(i);
    
// 출력
foreach (int num in list)
	Console.WriteLine(num);
    
// 삽입
list.Insert(index, value);
    
// 삭제
list.Remove(value); // 처음 만난 애만 삭제
list.RemoveAt(index); // 해당 index 삭제
list.Clear(); // 전체 삭제

Dictionary

Hash Table 이용 (Key로 Value를 바로 찾아줌)
→ 메모리 손해, 속도 이득

 class Monster
 {
 	public int id;
 
 	public Monster(int id) { this.id = id; }
 }
 
 static void Main(string[] args)
 {
 	Dictionary<int, Monster> dic = new Dictionary<int, Monster>();
 	dic.Add(1, new Monster(1));
 	dic[5] = new Monster(5); // id = 5인 Monster를 5번째에 넣어줌
 
 	// key 값에 맞는 value 찾기
 	// key에 직접 접근은 위험하므로 TryGetValue 사용
 	Monster mon;
 	bool found = dic.TryGetValue(20000, out mon);
 
 	// 삭제
 	dic.Remove(7777);
 	dic.Clear();
 }
profile
고양이가 운영하는 테크블로그

0개의 댓글