You do not need to use vectors. If you want to stick with simple arrays, you can do something like this:
int arr[] = new int[15]; unsigned int arr_length = 0;
Now, if you want to add an element to the end of the array, you can do this:
if (arr_length < 15) { arr[arr_length++] = <number>; } else {
It is not as short and sleek as the PHP equivalent, but it does what you tried to do. So that you can easily resize the array in the future, you can use #define.
#define ARRAY_MAX 15 int arr[] = new int[ARRAY_MAX]; unsigned int arr_length = 0; if (arr_length < ARRAY_MAX) { arr[arr_length++] = <number>; } else { // Handle a full array. }
This simplifies array management in the future. Changing 15 to 100, the size of the array will be correctly resized throughout the program. Please note that you will need to set the array to the maximum expected size, since you will not be able to change it after compiling the program. For example, if you have an array of size 100, you can never insert 101 elements.
If you will use elements from the end of the array, you can do this:
if (arr_length > 0) { int value = arr[arr_length--]; } else {
If you want to remove items from the beginning (e.g. FIFO), the solution becomes more complex. You also need a start and end index.
#define ARRAY_MAX 15 int arr[] = new int[ARRAY_MAX]; unsigned int arr_length = 0; unsigned int arr_start = 0; unsigned int arr_end = 0; // Insert number at end. if (arr_length < ARRAY_MAX) { arr[arr_end] = <number>; arr_end = (arr_end + 1) % ARRAY_MAX; arr_length ++; } else { // Handle a full array. } // Read number from beginning. if (arr_length > 0) { int value = arr[arr_start]; arr_start = (arr_start + 1) % ARRAY_MAX; arr_length --; } else { // Handle an empty array. } // Read number from end. if (arr_length > 0) { int value = arr[arr_end]; arr_end = (arr_end + ARRAY_MAX - 1) % ARRAY_MAX; arr_length --; } else { // Handle an empty array. }
Here we use the module operator (%) to force the indices to turn around. For example, (99 + 1)% 100 is 0 (wrapping increment). And (99 + 99)% 100 equals 98 (decrement of wrap). This allows you to avoid statements and make code more efficient.
You can also quickly see how useful #define is, as your code becomes more complex. Unfortunately, even with this solution, you can never insert more than 100 elements (or any other maximum value) into an array. You also use 100 bytes of memory, even if only 1 element is stored in the array.
This is the main reason others have recommended vectors. The vector is managed behind the scenes, and new memory is allocated as the structure expands. It is still not as efficient as an array in situations where the size of the data is already known, but for most purposes, performance differences will not matter much. There are tradeoffs for each approach, and it is best to know both.