공부/Unity
[Unity] 자료구조 List, LinkedList, Dictionary
굴러다니다니
2025. 5. 23. 17:36
List
binarysearch가 더 찾는데는 빠르지만 정렬되어있는 배열이어야 한다는 조건이 있다.
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Insert(3, 10);
list.RemoveAt(0);
list.Remove(2);
list[0] = 9;
for (int i =0; i < list.Count; i++)
{
print($"for loop:{list[i]}");
}
//list.Sort();
foreach (var a in list)
{
print($"foreach loop:{a}");
}
var idx = list.IndexOf(10);
if (idx >= 0) print($"IndexOf(10) {idx}번에 존재");
idx = list.BinarySearch(10);
if (idx >= 0) print($"BinarySearch(10) {idx}번에 존재");
list.Clear();
LinkedList
LinkedList<데이터 타입> 변수명
추가 / 삭제가 빠르지만 검색이 느림
랜덤 액세스 불가 ([인덱스]로 참조 못함)
공간 재할당 발생 X
배열은 메모리 공간이 연속되어야 하지만, 링크드 리스트는 연속되지 않아도 가능.
하지만 연속되지 않기 때문에 배열 인덱스 사용 불가
Dictionary
Dictionary <키 타입, 값 타입> 변수명
키 값을 해싱(계산)하면 배열(버킷) 인덱스가 나옴
버킷 인덱스가 충돌하면, 해당 버킷은 링크드 리스트 형태로 항목이 추가됨
var dict = new Dictionary<int, string>();
dict.Add(1, "1번");
dict.Add(2, "2번");
dict.Add(3, "3번");
dict.Add(4, "4번");
dict.Remove(2); //key가 2인 값 삭제
dict[3] = "3번 변경"; //3이 key인 value 변경
foreach (var pair in dict)
{
print($"foreach loop:key{pair.Key} value:{pair.Value}");
}
string value = null;
if (dict.TryGetValue(3, out value))
print($"TryGetValue(3) {value} 존재");
if (dict.ContainsKey(3))
print($"ContainsKey(3) 존재");
dict.Clear();
728x90
반응형