deleting array elements in dynamic

at the start user receives the size of array , memmory is being allocated, you have to fill the array with numbers etc , you also receives number x , every single element in array which is >= x/2 wont be used anymore , so i want to delete him from the array and also the array size will be decreased , how do i do that ?


1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
 int main(){
int sizeofarray,x;
        cin>>sizeofarray;
	array = new int[sizeofarray];
	cin >> x;
	for (int q = 0; q < sizeofarray; q++) {
		cin >> arrray[q];//filling the array
	}
}
Last edited on
I dont see where array is declared .

To decrease the size you have to copy the sub-array into another and delete this one , then assign the new array to this array .

You should change the name by something else since this name is already taken.

Also there is no checking that sizeOfArray is unsigned and not null .
Last edited on
its just "pseudo code" im sure there is another way ,
stl vector containers are one of the fastest data structure in c++ , still it use this approach . Have you ever implemented a vector container class ?

this is what vector implementation could look like when adding a new element that exceed the container capacity :

1
2
3
4
5
6
7
8
9
10
11
int newCapacity = Capacity * 2;
int* newArray = new int[newCapacity];
for (int i = 0; i < nElements; ++i)
{
newArray[i] = data[i];
}
newArray[nElements] = element;
nElements++;
delete[] data;
data = newArray;
Capacity = newCapacity;
Topic archived. No new replies allowed.