So if I set a size variable to 10 and created an array int a[size], I can later change size to the number of inputs, and the array's size will change to that number as well right? |
In c++ an array size is a constant, not a variable.
You might write
though it is better practice to write
1 2
|
const int size = 10;
int arr[size];
|
In both cases, the size of the array is a constant which is known at compile-time. It cannot be later changed.
What you might do instead is to use a separate variable such as
int count = 0;
to keep track of how many elements are currently in use. Example,
1 2 3 4 5 6
|
const int size = 10;
int arr[size];
arr[0] = 2;
arr[1] = 3;
arr[2] = 5;
int count = 3;
|
Note,
count
may be changed (within the constraints of the array size) but
size
is fixed and cannot be changed.
Using vectors, things become a lot easier, as it will automatically keep track of its own size - and that size can be changed as necessary.
1 2 3 4
|
vector<int> vec;
vec.push_back(2);
vec.push_back(3);
vec.push_back(5);
|
You can find the size of the vector with
vec.size()