Use std::vector
, which is designed for exactly this use case.
The (rough) translation of the Perl code you have given to C++ using std::vector
would be something like this:
#include <iostream>
#include <vector>
int main() {
// Declare a vector that can only contain int values.
std::vector<int> numbers;
// Put the numbers [1,10] into the array.
for (int i = 1; i <= 10; ++i) {
numbers.push_back(i);
}
// Display the contents of the vector.
for (auto const &values : numbers) { std::cout << values << '\n'; }
return 0;
}
If you do not need the container allocations to be contiguous, std::deque
might perform better under certain access/modification patterns, as it makes multiple allocations and therefore does not require that the existing contents be copied when the container runs out of capacity.
2
solved How to form a dynamic array in C++?