C++/C++ 기타

C++ 동적으로 배열 크기를 늘리는 세가지 방법

kimc 2021. 6. 21. 23:05

 

이번 글을 통해 배워갈 내용

  1.  배열의 크기를 런타임에 늘려보겠습니다.
  2.  (세가지 방법)

첫번째 방법입니다.

	// 방법 1

	//10개의 원소를 가진 배열을 point 하는 oldArray1를 선언해줍니다.	
	int* oldArray1 = new int[10];

	//10개의 원소에 0부터 9까지 입력합니다.
	for(int i = 0; i < 10; i++ )
	{
		oldArray1[i] = i;
	}
	//이제 꽉 찼습니다.더 입력하려면 배열의 크기를 늘려야 합니다.

	//20개의 원소를 가진 배열을 point 하는 newArray1를 선언해줍니다.	
	int* newArray1 = new int[20];
	// oldArray1값을 newArray1에 넣어주고
	copy(oldArray1, oldArray1 + min(10, 20), newArray1);
	// oldArray1 메모리 해제 해줍니다.
	delete[] oldArray1;
	// 오래된 배열이 새로운 배열이 포인트 하는곳을 포인트 하고
	oldArray1 = newArray1;
	// 새로운 배열은 할당해제 해줍니다.
	newArray1 = NULL;
	// 값을 출력합니다.
	for (int i = 0; i < 12; i++)
	cout<<oldArray1[i] << " ";
	cout << endl;

 

 

두번째 방법입니다.

첫번째 방법과 동일하나

문법이 다릅니다.

	// 방법2
	int *oldArray2, *newArray2;

	oldArray2 = (int*)malloc(10 * sizeof(int));
	newArray2 = (int*)malloc(20 * sizeof(int));

	for (int i = 0; i < 10; i++)
	{
		oldArray2[i] = i;
	}


	for (int i = 0; i < 10; i++)
	{
		newArray2[i] = oldArray2[i];
	}

	free(oldArray2);
	oldArray2 = newArray2;
	newArray2 = NULL;

	for (int i = 0; i < 12; i++)
		cout<<oldArray2[i] << " ";

	cout << endl;

 

세번째 방법은 

벡터 라이브러리를 사용합니다

#include <vector>

 

벡터를 쓰면 편하게 가변 배열을 가지고 작업 할수있습니다.

	//방법3

	// 기본 값 0으로 초기화 된 원소 10개를 가진 벡터 
	vector<int> myVec(10);

	// 맨뒤에 11을 추가
	myVec.push_back(11);
	myVec.push_back(11);
	myVec.push_back(11);
	myVec.push_back(11);

	myVec.pop_back();

	for (const auto item : myVec) {
		cout << item << " ";
	}
	return 0;

 

전체 코드는 다음과 같습니다.

 

#include <iostream>
#include <vector>

using namespace std;

int main()
{

	// 방법 1

	//10개의 원소를 가진 배열을 point 하는 oldArray1를 선언해줍니다.	
	int* oldArray1 = new int[10];

	//10개의 원소에 0부터 9까지 입력합니다.
	for(int i = 0; i < 10; i++ )
	{
		oldArray1[i] = i;
	}
	//이제 꽉 찼습니다.더 입력하려면 배열의 크기를 늘려야 합니다.

	//20개의 원소를 가진 배열을 point 하는 newArray1를 선언해줍니다.	
	int* newArray1 = new int[20];
	// oldArray1값을 newArray1에 넣어주고
	copy(oldArray1, oldArray1 + min(10, 20), newArray1);
	// oldArray1 메모리 해제 해줍니다.
	delete[] oldArray1;
	// 오래된 배열이 새로운 배열이 포인트 하는곳을 포인트 하고
	oldArray1 = newArray1;
	// 새로운 배열은 할당해제 해줍니다.
	newArray1 = NULL;
	// 값을 출력합니다.
	for (int i = 0; i < 12; i++)
	cout<<oldArray1[i] << " ";
	cout << endl;

	// 방법2
	int *oldArray2, *newArray2;

	oldArray2 = (int*)malloc(10 * sizeof(int));
	newArray2 = (int*)malloc(20 * sizeof(int));

	for (int i = 0; i < 10; i++)
	{
		oldArray2[i] = i;
	}


	for (int i = 0; i < 10; i++)
	{
		newArray2[i] = oldArray2[i];
	}

	free(oldArray2);
	oldArray2 = newArray2;
	newArray2 = NULL;

	for (int i = 0; i < 12; i++)
		cout<<oldArray2[i] << " ";

	cout << endl;
	//방법3

	// 기본 값 0으로 초기화 된 원소 10개를 가진 벡터 
	vector<int> myVec(10);

	// 맨뒤에 11을 추가
	myVec.push_back(11);
	myVec.push_back(11);
	myVec.push_back(11);
	myVec.push_back(11);

	myVec.pop_back();

	for (const auto item : myVec) {
		cout << item << " ";
	}
	return 0;
}

결과

 

0 1 2 3 4 5 6 7 8 9 -842150451 -842150451
0 1 2 3 4 5 6 7 8 9 -842150451 -842150451
0 0 0 0 0 0 0 0 0 0 11 11 11

 

저는 안전성이 중요해서 가변 배열이 필요한 경우 3번째 방법을 많이 씁니다.

 

여러분은 어떤 방법을 주로 쓰시나요?

 

 

 


 

오늘도 즐거운 코딩하시길 바랍니다 ~ :)

 

참조 및 인용

https://stackoverflow.com/questions/12032222/how-to-dynamically-increase-the-array-size

 

How to dynamically increase the array size?

I've been trying to make a program that adds 2 arrays of different size. But I would like to know to to dynamically increase the array size capacity? Ex: array[4] then upgrade the size to 2 to make...

stackoverflow.com

https://stackoverflow.com/questions/49026147/dynamically-changing-array-size-in-c/49026327

 

Dynamically changing array size in C++

I need to transform an array from {4, 2 ,5} to {4, 2, 5, 4, 2, 5}. Here's my output: {4, 2, 5, 3.21143e-322, 0, 2}, which is obviously incorrect. But I cannot seem to figure out the issue in my log...

stackoverflow.com

https://www.cplusplus.com/reference/vector/vector/

 

vector - C++ Reference

difference_typea signed integral type, identical to: iterator_traits ::difference_type usually the same as ptrdiff_t

www.cplusplus.com

C++ Primer

728x90