Original Post
Hey everyone.
I'm writing a dynamic array in C++ just as practise (since I've never done it before). I have written a template class that creates an array of type X and fills it one at a time until it reaches capacity and then resizes (some code below). I have an iterator class that can iterate in either direction. Pushing and popping all works beautifully for my purposes. My issue is how to handle deleting elements at a random point in the array.
I saw an article on a random website that suggested shuffling the data in the array back one (seems time consuming). Also thought that I could memcopy the data to a temp location, then memcopy it back to restore contiguity, but again I think that may be costly. Another idea I had was to keep track of the number of deletes (and store dummy data in the array) and once it had exceeded a certain threshold I would run a resize to restore the contiguity of the array... but the thought of that makes me feel dirty and that would make iterating messy.
The goal here is to have a container that I can iterate in either direction, push and pop and delete at any index at any time and still maintain contiguity in memory. I don't expect to delete all that often (most of the time I'll be using push/pop) so I think I'll end up going with the 2xmemcopy method.
Any ideas?
Thanks for reading
I'm writing a dynamic array in C++ just as practise (since I've never done it before). I have written a template class that creates an array of type X and fills it one at a time until it reaches capacity and then resizes (some code below). I have an iterator class that can iterate in either direction. Pushing and popping all works beautifully for my purposes. My issue is how to handle deleting elements at a random point in the array.
I saw an article on a random website that suggested shuffling the data in the array back one (seems time consuming). Also thought that I could memcopy the data to a temp location, then memcopy it back to restore contiguity, but again I think that may be costly. Another idea I had was to keep track of the number of deletes (and store dummy data in the array) and once it had exceeded a certain threshold I would run a resize to restore the contiguity of the array... but the thought of that makes me feel dirty and that would make iterating messy.
The goal here is to have a container that I can iterate in either direction, push and pop and delete at any index at any time and still maintain contiguity in memory. I don't expect to delete all that often (most of the time I'll be using push/pop) so I think I'll end up going with the 2xmemcopy method.
Any ideas?
Thanks for reading