C++에서 개체 배열 초기화

Jinku Hu 2023년10월12일
  1. new연산자를 사용하여 C++에서 매개 변수화 된 생성자로 객체 배열 초기화
  2. std::vector::push_back함수를 사용하여 매개 변수화 된 생성자로 객체 배열 초기화
  3. std::vector::emplace_back함수를 사용하여 매개 변수화 된 생성자로 객체 배열 초기화
C++에서 개체 배열 초기화

이 기사에서는 C++에서 매개 변수화 된 생성자를 사용하여 객체 배열을 초기화하는 여러 방법을 보여줍니다.

new연산자를 사용하여 C++에서 매개 변수화 된 생성자로 객체 배열 초기화

new연산자는 C++ 동적 메모리 관리 인터페이스의 일부이며 C 언어의malloc함수와 동일합니다. 동적 메모리 관리는 사용자가 지정된 고정 크기의 메모리를 할당하고 더 이상 필요하지 않을 때 시스템에 반환하는 흐름을 수반합니다.

new는 시스템에서 고정 된 바이트 수를 요청하는 데 사용되며, 호출이 성공하면 메모리 영역에 대한 포인터를 반환합니다. 다음 예제에서는 데이터 멤버를 콘솔에 출력하기 위해 두 개의 생성자와 printPair가있는 Pair라는 클래스를 정의했습니다. 처음에는new 연산자를 사용하여Pairs의 네 멤버 배열을 할당해야합니다. 다음으로 for루프를 사용하여 배열을 순회 할 수 있으며 각 반복은 매개 변수화 된 생성자로 요소를 초기화합니다. 하지만 할당 된 배열은delete 연산자를 사용하여 프로그램이 종료되기 전에 해제되어야합니다. 또한 배열의 각 요소를 할당 해제하려면delete []표기법이 필요합니다.

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

class Pair {
  int x, y;

 public:
  Pair() = default;
  Pair(int a, int b) : x(a), y(b) {}

  void printPair() const { cout << "x: " << x << endl << "y: " << y << endl; }
};
int main() {
  Pair *arr = new Pair[4];

  for (int i = 0; i < 4; ++i) {
    arr[i] = Pair(i * 2, i * i);
  }

  for (int i = 0; i < 4; ++i) {
    arr[i].printPair();
  }

  delete[] arr;
  return EXIT_SUCCESS;
}

출력:

x: 0
y: 0
x: 2
y: 1
x: 4
y: 4
x: 6
y: 9

std::vector::push_back함수를 사용하여 매개 변수화 된 생성자로 객체 배열 초기화

또는 헤드리스 접근 방식은 새 요소를 동적으로 초기화하는 내장 함수를 제공하는std::vector컨테이너에 객체를 저장하는 것입니다. 즉,Pair정의는 동일하게 유지되지만 반복 할 때마다push_back함수를 호출하고 두 번째 생성자의Pair값을 전달합니다. 장점은 메모리 리소스의 할당 해제에 대해 걱정할 필요가 없다는 것입니다. 자동으로 정리됩니다.

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

class Pair {
  int x, y;

 public:
  Pair() = default;
  Pair(int a, int b) : x(a), y(b) {}

  void printPair() const { cout << "x: " << x << endl << "y: " << y << endl; }
};
int main() {
  vector<Pair> array;

  for (int i = 0; i < 4; ++i) {
    array.push_back(Pair(i * 2, i * i));
  }

  for (const auto &item : array) {
    item.printPair();
  }

  return EXIT_SUCCESS;
}

출력:

x: 0
y: 0
x: 2
y: 1
x: 4
y: 4
x: 6
y: 9

std::vector::emplace_back함수를 사용하여 매개 변수화 된 생성자로 객체 배열 초기화

매개 변수화 된 생성자를 사용하여 객체 배열을 초기화하는 또 다른 방법은std::vector클래스의emplace_back함수를 활용하는 것입니다. 이러한 방식으로Pair생성자의 값만 전달하면emplace_back이 자동으로 새 요소를 생성합니다. 이전 방법과 마찬가지로이 방법도 사용자가 메모리 관리에 대해 걱정할 필요가 없습니다.

#include <iostream>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

class Pair {
  int x, y;

 public:
  Pair() = default;
  Pair(int a, int b) : x(a), y(b) {}

  void printPair() const { cout << "x: " << x << endl << "y: " << y << endl; }
};
int main() {
  vector<Pair> array;

  for (int i = 0; i < 4; ++i) {
    array.emplace_back(i * 2, i * i);
  }

  for (const auto &item : array) {
    item.printPair();
  }

  return EXIT_SUCCESS;
}

출력:

x: 0
y: 0
x: 2
y: 1
x: 4
y: 4
x: 6
y: 9
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - C++ Array