Reputation: 387
If I have for example array of pointers (which is full) with 5 elements and I want to insert another element at second position, I would have to allocate another array (with size+1), copy first element from an old array, insert new element, and then copy remaining elements. This application can't waste any space. This is the code so far:
Sometype **newArray=new Sometype*[++Count];
size_t s=sizeof(Array);
memcpy(newArray,Array,s*position);
newArray[position]=new Sometype();
memcpy(newArray+position+1,Array+position,s*(Count-position-1));
delete [] Array;
Array=newArray;
Is there any more efficient method to do this thing because this is a bottleneck for my application?I'm new to c++ so I don't know any advanced stuff. Could vector be used for this purpose? I think I read somewhere that it takes double of previous used space when it's resizing. Is this true or this behavior can be modified?
Upvotes: 0
Views: 792
Reputation: 133072
If you can't waste any space and you have to stick to sequential containers, then I'm afraid this is the most efficient way. But I still don't believe that you can't waste any space. If you can anticipate in advance that you will need to later add 5 more elements, then having your array resized from the beginning will prove much more effective. In any case, you should use vector to avoid this awful C-style code and be more clear with your intents. You might want to take a look at std::vector<T>::reserve()
function. Whether or not vector takes double of previous when it's resizing is unspecified and varies across implementations.
Upvotes: 3
Reputation: 68698
Have a look at the standard containers std::vector
, std::list
, std::unordered_set
and std::unordered_map
Upvotes: 3