Home  >  Article  >  How to create a dynamic array in c++

How to create a dynamic array in c++

小老鼠
小老鼠Original
2024-05-02 09:54:16736browse

There are four ways to create dynamic arrays in C: using std::vector. Use new and delete. Use template metaprogramming. Use boost library.

How to create a dynamic array in c++

How to create a dynamic array in C

Dynamic array, also known as variable array or vector, is a A data structure whose size can be changed at runtime. In C, you can create dynamic arrays using the following methods:

1. Use the built-in std::vector

<code class="cpp">#include <vector>

int main() {
  // 创建一个整型动态数组,初始大小为 0
  std::vector<int> numbers;

  // 向数组中添加元素
  numbers.push_back(1);
  numbers.push_back(2);
  numbers.push_back(3);

  // 输出动态数组中的元素
  for (int number : numbers) {
    std::cout << number << " ";
  }

  return 0;
}</code>

2. Use new and delete

<code class="cpp">int* numbers = new int[size];
// 操作动态数组

delete[] numbers;</code>

3. Use template metaprogramming

<code class="cpp">template <typename T, size_t Size>
struct Array {
  T data[Size];
};

int main() {
  // 创建一个大小为 3 的整型动态数组
  Array<int, 3> numbers;

  // 操作动态数组

  return 0;
}</code>

4. Use boost library

<code class="cpp">#include <boost/array.hpp>

int main() {
  // 创建一个大小为 3 的整型动态数组
  boost::array<int, 3> numbers;

  // 操作动态数组

  return 0;
}</code>

The above is the detailed content of How to create a dynamic array in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn