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?

2/22/2012 6:51:45 PM

Accepted 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;

4/26/2013 7:30:38 PM

Arrays in C++ cannot change size at runtime. For that purpose, you should use vector<int> instead.

vector<int> arr;

// arr.size() will be the number of elements in the vector at the moment.

As mentioned in the comments, vector is defined in vector header and std namespace. To use it, you should:

#include <vector>

and also, either use std::vector in your code or add

using std::vector; 


using namespace std;

after the #include <vector> line.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow