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;
You can use a variable to count places in the array, so when ever you add a new element, you put it in the right place. For example:
int a = 0;
int arr[5] = { };
arr[a] = 6;
a++;
I may be missing the point of your question here, and if so I apologize. But, if you're not going to be deleting any items only adding them, why not simply assign a variable to the next empty slot? Every time you add a new value to the array, just increment the value to point to the next one.
In C++ a better solution is to use the standard library type std::list< type >
, which also allows the array to grow dynamically, e.g.:
#include <list>
std::list<int> arr;
for (int i = 0; i < 10; i++)
{
// add new value from 0 to 9 to next slot
arr.push_back(i);
}
// add arbitrary value to the next free slot
arr.push_back(22);
I fully agree with the vector
way when implementing a dynamic array. However, bear in mind that STL provides you with a host of containers that cater to different runtime requirements.You should choose one with care. E.g: For fast insertion at back you have the choice between a vector
and a deque
.
And I almost forgot, with great power comes great responsibility :-) Since vector
s are flexible in size, they often reallocate automagically to adjust for adding elements.So beware about iterator invalidation (yes, it applies as well to pointers). However, as long as you are using operator[]
for accessing the individual elements you are safe.
Use a vector:
#include <vector>
void foo() {
std::vector <int> v;
v.push_back( 1 ); // equivalent to v[0] = 1
}
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);