Hi,
I was wondering if it is possible to delete an element from an array of objects. If so, can anyone give me a few pointers on how? I don't think using delete[] would work in this case?
Hi,
I was wondering if it is possible to delete an element from an array of objects. If so, can anyone give me a few pointers on how? I don't think using delete[] would work in this case?
Arrays are of fixed length. You can nullify the data for a given array element, but you can't, per se, "delete" an array element once an array is created of a given size.
In C++ there are also vectors, and they can be of varying size and changed dynamically when a program runs.
Todd
Ok... Seems solid, what about trying something along the lines of:
...but it appears to do nothing. I apologize for taking up your time with these questions, I'm fairly new to programming.Code:bool deleteEntry (string nameToDelete) { for (int i = 0; i < numEntries; i++) { Telephone *b = NULL; if (nameToDelete == entries[i].getName()) { b = new Telephone (entries[i]); return true; } } return false; }
There's a lot of information not there.
We don't know what kind of container entries[] is.
If the purpose of the function is to delete an entry, for one thing, it's not deleting anything. Rather, it actually acquires a new instance of a Telephone object, but then does nothing with it (that is apparent from this code fragment).
What's your question?
Why do you expect it to do anything? You copy the telephone entry you want to delete to another pointer. Why would that delete the first one? (Granted, the second one gets deleted when it goes out of scope when the function ends, but that doesn't take the first one with it.)
If entries is a vector, you can use erase. If entries is an array, then entries[i] will always and forever exist (as long as the array does), but I suppose you can blank out its contents using ... well, whatever it is you use to change things in Telephone.
entries[] is an array of telephones. Each element in the array contains a person's name + area code + telephone number. The idea is to nullify the data for a given element as you said but I'm not sure how to go about that.
If you want to do it manually, then you'll need to copy each entry beyond the one that you found down by one position. And decrement numEntries.
If you used a vector instead of array, it might be easier to use the alternative: algorithms + vector::erase.
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
You may want to use a linked list instead of a vector/array if you wish to frequently delete objects in the middle without keeping a bunch of nullified objects in the array.