How to create a dynamic array in C++?

by princess.fritsch , in category: C/C++ , 2 years ago

How to create a dynamic array in C++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by brisa , 2 years ago

@princess.fritsch I think you can use new int in C++ to create a dynamic array, take a look code below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    int array_size;
    // Enter size of array
    std::cin >> array_size;


    int* arr = new int[array_size];
    for (int i = 0; i < array_size; i++) {
        arr[i] = i;
        
        std::cout << "Array index " << i << " contains " << arr[i] << std::endl;
    }

    return 0;
}


Member

by uriah , a year ago

@princess.fritsch 

In C++, a dynamic array can be created using the std::vector class. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>

int main() {
  std::vector<int> v;
  
  // Add elements to the vector
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  
  // Print the size of the vector
  std::cout << "Size of vector: " << v.size() << std::endl;
  
  // Access elements of the vector using the [] operator
  std::cout << "v[0] = " << v[0] << std::endl;
  std::cout << "v[1] = " << v[1] << std::endl;
  std::cout << "v[2] = " << v[2] << std::endl;
  
  return 0;
}


This will output the following:

1
2
3
4
Size of vector: 3
v[0] = 1
v[1] = 2
v[2] = 3


The std::vector class has many other useful member functions, such as insert, erase, clear, and more. You can find more information about std::vector in the C++ documentation or by doing a search online.