tags:

views:

95

answers:

4
+2  Q: 

PUSH an array C++?

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

+7  A: 

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().

+1: use std::vector for dynamically sized array needs.
DeadMG
I would say use vector for any array.
Kugel
+4  A: 

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
// ...
Cedric H.
+1: This example helped me, thankyou
Greg Treleaven
+1  A: 

Use a std::vector. You cannot push into a C style array e.g. int[].

celavek
+1  A: 

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

  1. Is there at least one unused slot at the end of the array?
  2. 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.

Johann Gerell