Dynamic Array Size

Hello,

I am new to C++ so my appologies for the silly question.
I have a question about dynamic arrays. In Savitch Absolute C++, it is mentioned that one of the advantages of dynamic arrays is that we don't need to estimate the size of the array beforehand.
However I have a function that loops through an array and checks which elements satisfy a certain condition and extracts them into a new array. In this case we don't know how many elements satisfy the condition and thus we don't what is the size of the array that will hold the extracted elements. So one would need to resort to a dynamic array. However I am not sure that I am using dynamic array correctly as I have to loop twice through the array I am extracting elements from. Once to figure out the size of array and another time to extract the elements satisfying the condition. Please see code below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void extract (int myArray[], int size)
{
int dynamicArraySize=0;

for (int i=0; i<size; i++)
{
if (condition)
dynamicArraySize++;
}
int* dynamicArray = new int[dynamicArraySize]
for (int i=0,j=0; i<size; i++)
{
if (condition)
{
dynamicArray[j]=myArray[i];
j++;
}
}
}
You could make a temporary array that holds extracted values, size equal to the normal array. Enumerate the size of the dynamic array at the same time as you extract them. Then transfer the data from the temporary array to the dynamic array.
Edit: Nevermind, I misunderstood...by a lot.
Last edited on
Thanks for the replies. I have mentioned, it is impossible to knwo the size of the array that will hold the data because it is impossible to know how many elements satisfy the condition. I think my code or Zhuge suggestions might be the simplest solutions.
Topic archived. No new replies allowed.