Okay, so, say I have a template class which holds a pointer to a dynamically allocated array. The type of the array is determined by the template.
What I need is a way to "erase" an item from the array. Specifically, the last item (which is easier because you don't have to move around values). Say I have this function:
where arrayPtr is a pointer to the array and endValue is an int which holds the subscript of the array's last element.
But since I don't know the type of the array, I can't just set it to NULL or 0 (what if it's a string?). I even tried allocating a new object of type T, and assigning it to the array's item, but that failed with an access violation error.
Try with T(), it is the default value of 'T' but this shouldn't work if 'T' has only constructors which need some arguments.
You should try STL containers, some have a method called 'pop_back' which removes the last element
Yeah, of course I would use an STL class for an actual implementation. After all, it'd be much more versatile than anything I could write up in time. The problem is that I was specifically asked to do it this way as an assignment...
And now that I think about it, I may have just had an off-by-one error on the pointer's subscript... I have another function that adds a value to the end of the array, and updates the endpoint marker, so I may have tried writing past the end of the array.
I'll try using T() when I get home. Would you just write it like: arrayPtr[endValue] = T();
Or would I have to instantiate a temporary variable and then assign it to the array?
Turns out it was a simple off-by-one error. I had forgotten to decrement the array endValue before using it as a subscript. I changed that, and used T(), and it worked perfectly.
Thanks again!