If I were to form an array of integers in C++, I know that I could do it like this:
#include <iostream>
using namespace std;
int main()
{
int numbers[] = {1,2,3,4,5,6,7,8,9,10};
for(int i = 0; i < 10; i++){cout << i << " ";}
return 0;
}
Executing the above C++ code just prints the integers 1 to 10 with a space separating each integer.
So I don't access memory space outside of the array it's good practice to declare the integer size of the array, so it would normally be declared as int numbers[10] = {1,2,3,4,5,6,7,8,9,10};
... but that's not necessary, as the array of integers can be accessed with a range based for loop.
However, this involves declaring an array, usually with the size, or if you don't give it the size (number of elements), then you have to immediately specify what the elements are in the array, and then C++ determines the size. This is a static array.
What I'm interested in is dynamic arrays in which you do not have to declare the size of the array to begin with or immediately fill it with elements, but you can later add items to the array. Considering an array of integers, I like to do this trick in Perl:
use strict;
use warnings;
my @numbers = (); # Declare an array without declaring its size or elements.
for(my $i = 1; $i <= 10; $i++)
{
push @numbers, $i; # Dynamically form the @numbers array with values 1 to 10.
}
while(my $values= <@numbers>){print "$values";} # Print every value in the array of numbers.
Executing the following Perl code produces this output:
1 2 3 4 5 6 7 8 9 10
This is the contents of the @numbers array from element 0 to 9. You can see that it was formed dynamically.
In Perl arrays are declared with the "@" symbol and singular variables are referred to with the "$" symbol. I didn't use Perl for any particular reason besides the fact that I know how to form dynamic arrays with it.
I would like to know if there is any way in which in C++ that dynamic arrays can be formed. Perhaps by using special libraries that include new functions?
Thanks!