How would I dynamically add a value (push) to an array? I could do this in AS3, but I can't find a function for it in C++.
if it's a statically defined array, like "int array[10];", you can't, its size is fixed. If you use a container such as std::vector, you'd use std::vector::push_back().
It is not possible to 'push' in a statically allocated classic C-style array and it would not be a good idea to implement your own 'method' to dynamically reallocate an array, this has been done for you in the STL, you can use vector
:
#include <vector>
// ...
std::vector<int> vect;
vect.push_back(1);
vect.size(); // --> 1
vect.push_back(2);
vect.size(); // --> 2
// ...
Use a std::vector. You cannot push into a C style array e.g. int[].
Assuming you don't mean a std::vector<>
, where you obviously would use std::vector<>::push_back()
, but an actual array, then you need to know
- Is there at least one unused slot at the end of the array?
- Yes? then put the value at the first unused slot. No? Allocate memory for a new array that is at least the size of the previous plus any amount of additional slots that you want, copy the old values over there and add the new value.
The above of course implies that you know where in the available memory the last used slot resides.
This is what std::vector<>
is for, you know.