So I need to make a function to delete all elements of a dynamically allocated array (found in my program's default constructor), and I am wondering how to do so. A function to remove any element at any index was already provided for me:
template<typename elemType>
void arrayListType<elemType>::removeAt(int location) {
if (location < 0 || location >= length) {
cout << "The location of the item to be removed ";
cout << "is out of range." << endl;
}
else {
for (int i = location; i < length - 1; i) {
list[i] = list[i 1];
}
--length;
}
}
Is there any way I can use this method as a way to remove every element to make the size 0?
CodePudding user response:
Given that the elements of list
past length
are copies of the "live" elements, the simplest way would be to set length to 0.
template<typename elemType>
void arrayListType<elemType>::removeAll() {
length = 0
}
The naive way of implementing it in terms of removeAt
is to remove the first element until there are none left
template<typename elemType>
void arrayListType<elemType>::removeAll() {
while (length) removeAt(0);
}
However that will do a bunch of unnecessary copying, so it's more effective to remove the last element each time
template<typename elemType>
void arrayListType<elemType>::removeAll() {
while (length) removeAt(length-1);
}
CodePudding user response:
To just delete the whole array you can use delete[] arr;
And if you want to just delete each element, you can do something like this:
for(int i = 0; i < arr_size; i ){
delete arr[i];
}