D
D
Dmitry Shevchenko2021-12-16 21:17:29
C++ / C#
Dmitry Shevchenko, 2021-12-16 21:17:29

How to expand array c++ (add element)?

In the loop, I get up to 10k values ​​that need to be quickly written to the array, while I don’t know exactly how many there will be, but there should not be empty values. If I define an array with length 1 , then how to expand (complement) it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-12-16
@shevczik

Use std::vector. It expands automatically and is fast at the same time.

N
nishe, 2021-12-16
@nishe

In the case when you need to expand the array, you can, for example, use the realloc() function.
It will be like this:
Instead of int, you put the data type you are working with. plus_one_element will allocate plus one memory location for the number at each step of the for loop. Then in arr[plus_one_element - 1] you write down the desired value. We do minus one, since the array is initialized from scratch. Read about dynamic arrays and realloc.

for (int plus_one_element = 1; plus_one_element < 10001; plus_one_element++) 
     arr = (int*)realloc(arr, plus_one_element*sizeof(int))
     std::cin << arr[plus_one_element - 1];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question