Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PUSH an array C++?

Tags:

c++

arrays

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++.

like image 904
Greg Treleaven Avatar asked Sep 29 '26 02:09

Greg Treleaven


2 Answers

You can't if it's a statically defined array like so:

int array[10];

Its size is fixed. However, if you use a container such as std::vector you'd use:

std::vector::push_back()
like image 125
Eugene Smith Avatar answered Sep 30 '26 17:09

Eugene Smith


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
// ...
like image 45
Cedric H. Avatar answered Sep 30 '26 15:09

Cedric H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!