+ 1

Dynamic array in c++

Hi We do have to store pointers in memory.those pointers are of class objects.. As number of object to be created are not sure, we just declared pointer to array of 10 object pointers (10 for example). When we need to do delete specific pointer of class object (in fact specific pointer of class object stored in array ) , what should be done... ? How to maintain size? I mean deleted entry should allow me to store 1 new object pointer with capacity 10 only as one we already deleted from pointer to array of pointer. How to achieve this...? P.s. : no vector stl is to be used.. New cls; of class object pointer is used for each item.. to store 10 such pointer, we did malloc of 10 pointer type object. How to implement delete functionality ? Feel free to ask for query in case it is not clear.

4th Feb 2020, 8:48 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Antworten
+ 2
If STL containers are not a choice, I would probably just maintain a second array of the same size that keeps tracks of which spots are occupied and which are free, e.g. an array of bools or a std::bitset<>. When a user wants to enter a record, you look in the second array for a free index, make an entry in the first arrax at that index and set the flag in the second array (or, if there is no free index, inform the user about it). For deletion, you just mark a spot in the second array as availaible again (and optionally, call the destructor on the affiliated object if necessary). Finally, when the user decides to quit, you delete the two arrays. Not sure if I understood everything correctly, so I hope this suits your needs. Sample: https://code.sololearn.com/cUD1CfM29lEm/?ref=app
4th Feb 2020, 10:26 PM
Shadow
Shadow - avatar
+ 3
When you delete an object, you could also move the whole right side of the array left by one to fill the gap. That way you can always write new entries to the end of the array. You can move the whole chunk of data with a single call to `memmove`!
4th Feb 2020, 11:11 PM
Schindlabua
Schindlabua - avatar
+ 2
Thank you Schindlabua and Shadow for your help.. :)
6th Feb 2020, 2:51 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
In short : user press one each time , create item class object and store Id and name provided by user.. When user press 2 each time, delete one of the object which we stored based on input. Input 1 for 11 time not allowed as we have capacity 10. But 11 time input 1 is allowed if user entered 2 once due to which one objet is already deleted from memory
4th Feb 2020, 8:52 PM
Ketan Lalcheta
Ketan Lalcheta - avatar