반응형
1. 2칸짜리 배열을 만들고, 3칸까지 값을 넣어본다.
2. 2칸에 값이 가득 찼기 때문에 인덱스 오류가 뜬다.
3. 수용량 * 2 의 양의 새로운 배열은 만들어준다.
4.하지만, 그냥 계속 늘리면 안되기 때문에 if 문을 사용하여서
count (인덱스의 양)이 수용양보다 크거나 같으면 새로운 배열을 만들어주기로한다.
5.그리고 4칸짜리 빈 temp 배열에 arr의 소요들을 집어 넣어준다.
6.arr 배열에 temp의 값을 집어 넣는다. // temp는 Add 인스턴스가 사라지면서 소멸하게 되고,
arr에 값이 변경이 된다.
----
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study16
{
public class DynamicArray
{
public int[] arr; // 배열을 만드는 것
public int capacity; // 배열이 수용할 수 있는 공간의 양
public const int GROWTH_FACTOR = 2; // 늘려줄 공간을 곱하는 양
public int count; // 배열의 꽉참을 알기 위한
public DynamicArray(int capacity)
{
this.capacity = capacity;
this.arr = new int[this.capacity];
}
public void Add(int element) {
if (this.count >= capacity) {
int newSize = this.capacity * GROWTH_FACTOR;
int[] temp = new int[newSize]; // 4칸 짜리의 배열을 만든다.
for (int i = 0; i < arr.Length; i++) {
temp[i] = arr[i]; // 옮겨 답는 과정
}
this.arr = temp; // arr를 temp의 값으로 바꿔준다. //temp는 사라짐
}
this.arr[count] = element;
count++;
}
public void Print() {
for (int i = 0; i < arr.Length; i++) {
Console.Write(" {0}", arr[i]);
}
Console.WriteLine(" ");
}
}
}
--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Study16
{
public class App
{
public App()
{
DynamicArray arr = new DynamicArray(2);
arr.Print();
Console.WriteLine("배열의 카운터 값 : {0}", arr.count);
arr.Add(5);
arr.Print();
Console.WriteLine("배열의 카운터 값 : {0}", arr.count);
arr.Add(3);
arr.Print();
Console.WriteLine("배열의 카운터 값 : {0}", arr.count);
arr.Print();
arr.Add(1);
Console.WriteLine("배열의 카운터 값 : {0}", arr.count);
arr.Print();
arr.Add(8);
Console.WriteLine("배열의 카운터 값 : {0}", arr.count);
}
}
}
반응형
'C# > 자료구조' 카테고리의 다른 글
0330_단일 연결리스트로 stack 구현하기 (0) | 2021.03.30 |
---|---|
0330 _ 고정배열로 Stack 구현하기 (0) | 2021.03.30 |
0330_단일 연결 리스트로 큐 구현하기 (0) | 2021.03.30 |
0330_원형배열을 사용한 큐 구현 (0) | 2021.03.30 |
0329 _ 단일연결 리스트 (2단계까지) / (0) | 2021.03.29 |