r4ccoon r4ccoon - 1 year ago 101
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
, 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 Source

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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download