Deleting an item in the middle of a large vector is expensive because all items after the deleted item must be shifted to the left.
In case the index of the item/the order is not important, we can delete the item in O(1) time.
void fast_erase(vector<int>& v, int idx){
if(idx < v.size()){
v[idx] = std::move(v.back());
v.pop_back();
}
}
Top comments (4)
That really should be:
you are right! template is better^^
Templates are just one thing. The other two things are that (1) you really should use
size_type
(or at leastsize_t
) and (2) you didn't take the degenerate case where the index ==size()-1
into account.thank you