shrink c++ vector
I would like to reduce a vector with 9 component to have only 7, throwing away the first and the last and keeping te rest, so that:
Can you help me to find an elegant way to do so, please?
Thanks a lot for your help!!
Copy the elements to where they should be, then use the resize() method. Note that this does NOT decrease the capacity of the vector. If you actually want to release some memory, you need to play the "swap trick."
Keep in mind that adding or deleting elements from a vector anywhere except at the end is relatively expensive since elements after the ones you add or delete have to be copied to their new locations. If you need to efficiently add or delete elements at both ends (but not in the middle) consider using a queue instead of a vector (the elements are not guaranteed to be contiguous in memory, but they probably consist of a small number of contiguous chunks, so cache efficiency should be reasonable). If you need to efficiently add/delete elements anywhere, you would need a list, but a list is much less cache-efficient since its elements may be widely scattered in memory, so avoid it unless your container is very large. If in doubt, profile.
Edit: Oops, I meant to say deque instead of queue, thanks iMalc.
If you just erase the two elements you no longer need the copying will be done for you. Use erase to erase the first element and pop_back to erase the last (maybe pop_back first to avoid an unnecessary copy of that last element).
Consider switching to a deque if you frequently remove from both ends, as it is faster for the remove-from-front operation.
You need to use the swap technique to remove excess capacity:
container<T>( c ).swap( c ); // the shrink-to-fit idiom to shed excess capacity
By using the two-iterator constructor for a vector, the first and last element can be erased and the capacity trimmed in one line:
std::vector<T>(v.begin() + 1, v.end() - 1).swap(v);
Of course, in removing only two elements, chances are slim that the capacity will be effected anyway. Besides, while it's an interesting conversation I don't think that the OP should care about capacity here, the example has only 9 elements.
I somehow doubt that OP is interested in reducing memory usage here, just removing the first and last element...
Anyway you'll need to check first if there is anything to erase from the vector.
Definitely - although if one wanted to erase a range of elements at the beginning, and another range at the end, the swap method would be more concise, in addition to offering the possibility of a capacity reduction (the alternative is to call erase() twice, once for each range). In the OP's case, though, it doesn't matter.
Originally Posted by Daved
Start = 1;
Stop = 7;
for(x=Start;x<Stop+1;x++) new_vector[x-Start] = old_vector[x];
If you want a new vector, rather than modifying the old one:
if (old_vec.size() > 1) //there has to be at least two items to remove