+ 2
How I can insert a nuber into an array?
array a[4] ={1,2,4}; how I can insert 3 into a array after 2.
4 Réponses
+ 2
the thing you are asking is list
List<Integers> nos = new arrayLists<Integers>;
nos.add[1];
nos.add[3];
nos.add[5];
nos.add[6];
nos.add[2, 89];
will makes nos=[1,3,89,5,6];
it's in java, c# but not in c++
+ 2
for C++
std::vector<int> arr { 1, 2, 4 };
arr.insert(std::begin(arr)+2, 3);
0
you can do this
a[2]= 3,
0
Arrays' size is static. If you really need to use an array, you would need to make a new one.
For the sake of the question though, here's a C# example. I suppose the array must remain ordered, and the position of where to insert the new value is not previously known.
int[3] arr = {1,2,4};
int newValue = 3;
Array.Resize(ref arr, arr.Length + 1); //This is not dynamic allocation, it is creating a new array and copying the data, then changing the reference to point to the new array
arr[arr.Length - 1] = newValue;
Array.Sort(arr);
If you want a list of data that will always be the same size use arrays. If not, use lists.