Erasing using an iterator from 'find' or 'remove'

I would like to know what is the best way to remove an element from a vector in C ++.

I have seen many times people using std :: remove to find and remove an item, and then use erase to remove the item from the vector.

But why is it better than using find to get the iterator of the item you want to remove, and then using erase with that iterator?

thanks

+7
source share
1 answer

std::findfollowed by vector::erasewill erase the first occurrence of the object with the given value from vector.

std::vector<int> vec{1,3,3,8,3,5};
vec.erase(std::find(vec.begin(), vec.end(), 3));
//vec == {1,3,8,3,5}

std::remove, vector::erase, vector.

std::vector<int> vec{1,3,3,8,3,5};
vec.erase(std::remove(vec.begin(), vec.end(), 3), vec.end());
//vec == {1,8,5}

, .

std::remove , ; , std::remove, vector::erase, , , std::find, vector::erase undefined.

, "find-erase", "remove-erase" . , , "find-move-pop_back" "partition-erase":

//find-move-pop_back
std::vector<int> vec{1,3,3,8,3,5};
*std::find(vec.begin(), vec.end(), 3) = std::move(vec.back());
vec.pop_back();

//partition-erase
std::vector<int> vec{1,3,3,8,3,5};
vec.erase(
    std::partition(vec.begin(), vec.end(), [](int v){return v == 3;}),
    vec.end());
+14

All Articles