As I know, if the order of the vector is not important, it is faster to use the swap
-pop_back
idiom for removing an single item from std::vector
. For example:
auto it = std::find(my_vec.begin(),my_vec.end(),SOME_VALUE);
std::swap(*it,my_vector.back());
my_vector.pop_back();
The previous example avoids copying many elements.
From the same perspective, if I want to call std::vector::erase
on a range which is represent the last n
items of a std::vector
, would it be optimised and behaves like multi pop_back
?
Example:
auto it = std::find(my_vec.begin(),my_vec.end(),SOME_VALUE);
my_vec.erase(it,my_vec.end()); // Erase everything from 'it' and beyond