How to add an element to a C ++ array?

I want to add int to an array, but the problem is that I do not know what the index is.

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

This code works because I know which index I assign, 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 cannot do this, it gives me a compiler error. What do you suggest?

+53
c ++ arrays
Apr 16 '09 at 12:05
source share
11 answers

It is not possible to do what you say in C ++ with simple arrays. The C ++ solution for this is using the STL library, which gives you std::vector .

You can use vector as follows:

 std::vector< int > arr; arr.push_back(1); arr.push_back(2); arr.push_back(3); 
+50
Apr 16 '09 at 12:09
source share

Arrays in C ++ cannot resize at runtime. For this you should use vector<int> .

 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 pointed out in the comments, vector is defined in the vector header and the std . To use it, you must:

#include <vector>

also use std::vector in your code or add

 using std::vector; 

or

 using namespace std; 

after the line #include <vector> .

+65
Apr 16 '09 at 12:07
source share

Use vector:

 #include <vector> void foo() { std::vector <int> v; v.push_back( 1 ); // equivalent to v[0] = 1 } 
+13
Apr 16 '09 at 12:09
source share
 int arr[] = new int[15]; 

The variable arr contains the memory address. At the memory address in the line there are 15 consecutive lines. They can be referenced with an index from 0 to 14 inclusive.

In php, I can just do it arr [] = 22; this will automatically add 22 to the next empty array index.

There is no concept of "next" when working with arrays.
One important thing, which I think is missing, is that as soon as the array is created, all elements of the array already exist. They are uninitialized, but they all already exist. Thus, you do not "fill" the elements of the array when you go, they are already filled, just with uninitialized values. Unable to check uninitialized element in array.

It looks like you want to use a data structure like queue or stack or vector .

+13
Apr 16 '09 at 12:12
source share

You do not need to use vectors. If you want to stick with simple arrays, you can do something like this:

 int arr[] = new int[15]; unsigned int arr_length = 0; 

Now, if you want to add an element to the end of the array, you can do this:

 if (arr_length < 15) { arr[arr_length++] = <number>; } else { // Handle a full array. } 

It is not as short and sleek as the PHP equivalent, but it does what you tried to do. So that you can easily resize the array in the future, you can use #define.

 #define ARRAY_MAX 15 int arr[] = new int[ARRAY_MAX]; unsigned int arr_length = 0; if (arr_length < ARRAY_MAX) { arr[arr_length++] = <number>; } else { // Handle a full array. } 

This simplifies array management in the future. Changing 15 to 100, the size of the array will be correctly resized throughout the program. Please note that you will need to set the array to the maximum expected size, since you will not be able to change it after compiling the program. For example, if you have an array of size 100, you can never insert 101 elements.

If you will use elements from the end of the array, you can do this:

 if (arr_length > 0) { int value = arr[arr_length--]; } else { // Handle empty array. } 

If you want to remove items from the beginning (e.g. FIFO), the solution becomes more complex. You also need a start and end index.

 #define ARRAY_MAX 15 int arr[] = new int[ARRAY_MAX]; unsigned int arr_length = 0; unsigned int arr_start = 0; unsigned int arr_end = 0; // Insert number at end. if (arr_length < ARRAY_MAX) { arr[arr_end] = <number>; arr_end = (arr_end + 1) % ARRAY_MAX; arr_length ++; } else { // Handle a full array. } // Read number from beginning. if (arr_length > 0) { int value = arr[arr_start]; arr_start = (arr_start + 1) % ARRAY_MAX; arr_length --; } else { // Handle an empty array. } // Read number from end. if (arr_length > 0) { int value = arr[arr_end]; arr_end = (arr_end + ARRAY_MAX - 1) % ARRAY_MAX; arr_length --; } else { // Handle an empty array. } 

Here we use the module operator (%) to force the indices to turn around. For example, (99 + 1)% 100 is 0 (wrapping increment). And (99 + 99)% 100 equals 98 (decrement of wrap). This allows you to avoid statements and make code more efficient.

You can also quickly see how useful #define is, as your code becomes more complex. Unfortunately, even with this solution, you can never insert more than 100 elements (or any other maximum value) into an array. You also use 100 bytes of memory, even if only 1 element is stored in the array.

This is the main reason others have recommended vectors. The vector is managed behind the scenes, and new memory is allocated as the structure expands. It is still not as efficient as an array in situations where the size of the data is already known, but for most purposes, performance differences will not matter much. There are tradeoffs for each approach, and it is best to know both.

+10
Dec 28 '15 at 23:40
source share

I completely agree with the vector method when implementing a dynamic array. However, keep in mind that STL provides you with a lot of containers that satisfy various runtime requirements. You must choose one with care. For example: for quick installation on the back, you have a choice between vector and a deque .

And I almost forgot, great responsibility comes with great force :-) Since vector are flexible in size, they are often redistributed automatically to adjust the addition of elements. So be careful with the invalidity of the iterator (yes, this also applies to pointers). However, while you use operator[] to access individual items, you are safe.

+6
Apr 16 '09 at 12:12
source share

Perhaps I missed my question here, and if so, then I apologize. But if you are not going to delete any elements by adding them, why not just assign a variable to the next empty slot? Each time you add a new value to the array, just increment the value to the next.

In C ++, the best solution is to use the standard library type std::list< type > , which also allows dynamic array growth, for example:

 #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); 
+2
Apr 16 '09 at 12:14
source share

Initialize all array elements with zeros first, then find zero to find an empty slot

+2
Apr 16 '13 at 16:10
source share

If you write in C ++, it is better to use data structures from the standard library, for example, for a vector.

C-style masks are very error prone and should be avoided whenever possible.

+1
Apr 16 '09 at 12:20
source share

You can use the variable to count the places in the array, so when you add a new element, you put it in the right place. For example:

 int a = 0; int arr[5] = { }; arr[a] = 6; a++; 
0
Jun 28 '19 at 5:24
source share

Well, if you do not initialize the length of the array, you can add an element to the array.

 int arr[] = {1,2,3,4,5}; int last_index = sizeof(arr)/sizeof(arr[0]); arr[last_index] = 6; 

The new array will contain a value from 1 to 6

0
Jul 11 '19 at 14:01
source share



All Articles