r4ccoon r4ccoon - 24 days ago 9
C++ Question

How to add element to C++ array?

I want to add an int into an array, but the problem is that I don't know what the index is now.

int[] arr = new int[15];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;


That code works because I know what index I am assigning to, but what if I don't know the index...

In PHP, I can just do
arr[]=22;
, which will automatically add 22 to the next empty index of the array. But in C++ I can't do that, it gives me a compiler error. What do you guys suggest?

jab jab
Answer

There is no way to do what you say in C++ with plain arrays. The C++ solution for that is by using the STL library that gives you the std::vector.

You can use a vector in this way:

std::vector< int > arr;

arr.push_back(1);
arr.push_back(2);
arr.push_back(3);