I have a sorted std::vector of relative small size ( from 5 to 20 elements ).
I used std::vector since the data is continuous so I have speed because of cache.
On a specific point I need to remove an element from this vector.
I have now a doubt: which is the fastest way to remove this value between the 2 options below?
- setting that element to 0 and call
sortto reorder: this has complexity but
elements are on the same cache line. - call
erasethat will copy ( or memcpy who knows?? ) all elements after it
of 1 place ( I need to investigate the behind scense of erase ).
Do you know which one is faster?
I think that the same approach could be thought about inserting a new element without hitting the max capacity of the vector.
Regards
AFG
If you don’t care about the order of elements, you may be able to swap the element with the last one.
You mention setting the element to 0. If that means you have pointers, then you may not need the swap:
If you do care about the order, then your second option of using using erase() will preserve it and do the minimum amount of work. It will almost certainly be faster than resorting.