초록색이젤다 2025. 4. 21. 20:10

https://github.com/applejin0105/DataStructure/blob/e1c6dde7f506c76e6fc676a15f2f92fb46fda7cf/Header/Array.h

 

DataStructure/Header/Array.h at e1c6dde7f506c76e6fc676a15f2f92fb46fda7cf · applejin0105/DataStructure

자료구조 연습. Contribute to applejin0105/DataStructure development by creating an account on GitHub.

github.com

특징

  • T 타입의 객체를 저장할 수 있는 동적 배열
  • 삽입/삭제/검색 기능 제공
  • 내부 용량 자동 확장 및 축소.
  • C++ 스타일 반복자 지원 (begin(), end()) : Iterator
  • Resize 함수로 동적 메모리 관리.
Array() 생성자 기본 용량으로 메모리 할당
~Array() 소멸자 동적으로 할당된 메모리 해제
Capacity() int 현재 배열의 용량 반환
IsFull() bool 배열이 꽉 찼는지 확인
IsEmpty() bool 배열이 비어 있는지 확인
Get(i, out) bool 인덱스 i 위치의 값을 out에 반환 (실패 시 false)
Set(i, val) void 인덱스 i에 값을 설정 (범위 초과 시 무시)
Add(val) bool 배열 끝에 값을 추가 (용량 초과 시 resize)
Insert(i, v) bool 인덱스 i에 값을 삽입 (뒤로 shift)
Remove(v) bool 값 v를 찾아 제거
RemoveAt(i) bool 인덱스 i의 값을 제거 (뒤로 shift)
IndexOf(v, o) bool 값 v의 인덱스를 찾아 o에 저장
Contains(v) bool 값 v가 존재하는지 확인
Clear(r) void 배열을 초기화 (선택적으로 메모리도 재할당)
Resize(n) void 내부 배열의 크기를 n으로 재할당
begin() Iterator 반복자의 시작 반환
end() Iterator 반복자의 끝 반환

 

Test

#include <iostream>
#include "Array.h"

using namespace std;

void PrintArray(Array<int>& arr)
{
	cout << "Array Contents: ";
	for (auto val : arr)
	{
		cout << val << " ";
	}
	cout << "\nSize: " << (arr.IsEmpty() ? 0 : arr.Capacity()) << endl;
	cout << "------------------------\n";
}

int main()
{
	Array<int> arr;

	cout << "[1] Add Test\n";
	arr.Add(10);
	arr.Add(20);
	arr.Add(30);
	PrintArray(arr);

	cout << "[2] Insert Test (at index 1)\n";
	arr.Insert(1, 15); // Should insert 15 between 10 and 20
	PrintArray(arr);

	cout << "[3] Get and Set Test\n";
	int value;
	if (arr.Get(2, value)) {
		cout << "Value at index 2: " << value << endl;
	}
	arr.Set(2, 25); // Change 20 to 25
	PrintArray(arr);

	cout << "[4] IndexOf and Contains Test\n";
	int index = -1;
	if (arr.IndexOf(25, index)) {
		cout << "Found 25 at index: " << index << endl;
	}
	cout << "Contains 15? " << (arr.Contains(15) ? "Yes" : "No") << endl;

	cout << "[5] Remove by value Test (remove 15)\n";
	arr.Remove(15);
	PrintArray(arr);

	cout << "[6] RemoveAt Test (remove index 1)\n";
	arr.RemoveAt(1);
	PrintArray(arr);

	cout << "[7] Iterator Test (for range loop)\n";
	for (auto x : arr) {
		cout << x << " ";
	}
	cout << endl;

	cout << "[8] Clear Test (without memory reset)\n";
	arr.Clear();
	cout << "Is Empty? " << (arr.IsEmpty() ? "Yes" : "No") << endl;

	cout << "[9] Add after Clear + Resize Shrink Test\n";
	for (int i = 1; i <= 100; ++i) arr.Add(i);
	PrintArray(arr);

	cout << "[10] RemoveAt until shrink\n";
	for (int i = 0; i < 95; ++i) arr.RemoveAt(0);
	PrintArray(arr);

	return 0;
}