Program Club

정수의 동적 배열을 만드는 방법

proclub 2020. 11. 6. 20:56
반응형

정수의 동적 배열을 만드는 방법


new키워드를 사용하여 C ++에서 정수의 동적 배열을 만드는 방법은 무엇입니까?


int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

delete할당 하는 모든 어레이를 잊지 마십시오 new.


C ++ 11 이후로 다음 new[]delete[]달리 오버 헤드가 0 인 안전한 대안이 있습니다 std::vector.

std::unique_ptr<int[]> array(new int[size]);

C ++ 14에서 :

auto array = std::make_unique<int[]>(size);

위의 두 가지 모두 동일한 헤더 파일에 의존합니다. #include <memory>


표준 템플릿 라이브러리 사용을 고려할 수 있습니다. 간단하고 사용하기 쉬우 며 메모리 할당에 대해 걱정할 필요가 없습니다.

http://www.cplusplus.com/reference/stl/vector/vector/

int size = 5;                    // declare the size of the vector
vector<int> myvector(size, 0);   // create a vector to hold "size" int's
                                 // all initialized to zero
myvector[0] = 1234;              // assign values like a c++ array

int* array = new int[size];

동적 배열에 대한 질문이있는 즉시 가변 크기로 배열을 생성 할뿐만 아니라 런타임 중에 크기를 변경하기를 원할 수 있습니다. 여기에 예입니다 memcpy, 당신이 사용할 수있는 memcpy_sstd::copy뿐만 아니라. 컴파일러에 따라 <memory.h>또는 <string.h>필요할 수 있습니다. 이 기능을 사용할 때 새 메모리 영역을 할당하고 원래 메모리 영역의 값을 복사 한 다음 해제합니다.

//    create desired array dynamically
size_t length;
length = 100; //for example
int *array = new int[length];

//   now let's change is's size - e.g. add 50 new elements
size_t added = 50;
int *added_array = new int[added];

/*   
somehow set values to given arrays
*/ 

//    add elements to array
int* temp = new int[length + added];
memcpy(temp, array, length * sizeof(int));
memcpy(temp + length, added_array, added * sizeof(int));
delete[] array;
array = temp;

대신 상수 4를 사용할 수 있습니다 sizeof(int).


다음을 사용하여 일부 메모리를 동적으로 할당합니다 new.

int* array = new int[SIZE];

참고 URL : https://stackoverflow.com/questions/4029870/how-to-create-a-dynamic-array-of-integers

반응형