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; arr = 1; arr = 2; arr = 3; arr = 4; arr = 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?
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
You can use a
vector in this way:
std::vector< int > arr; arr.push_back(1); arr.push_back(2); arr.push_back(3);
Arrays in C++ cannot change size at runtime. For that purpose, you should use
vector<int> arr; arr.push_back(1); arr.push_back(2); // 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:
and also, either use
std::vector in your code or add
using namespace std;
#include <vector> line.