Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add element to C++ array?

Tags:

c++

arrays

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?

like image 289
r4ccoon Avatar asked Apr 16 '09 12:04

r4ccoon


People also ask

How do you add an element to the end of an array?

add("!"); List. add() simply appends an element to the list and you can get the size of a list using List.

Can you modify an array in C?

We can change the contents of array in the caller function (i.e. test_change()) through callee function (i.e. change) by passing the the value of array to the function (i.e. int *array). This modification can be effective in the caller function without any return statement.


1 Answers

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:

#include <vector>  std::vector< int > arr;  arr.push_back(1); arr.push_back(2); arr.push_back(3); 
like image 116
jab Avatar answered Oct 17 '22 23:10

jab