Erasing using iterator from 'find' or 'remove'

后端 未结 1 1272
孤城傲影
孤城傲影 2021-02-02 02:20

I would like to know what\'s the best practice to remove an element from a vector in C++.

I have seen many times people using std::remove to find and delete the element,

相关标签:
1条回答
  • 2021-02-02 03:08

    std::find followed by vector::erase will erase the first occurrence of an object with the given value from the 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 followed by vector::erase will remove every occurrence of an object with the given value from the 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}
    

    Neither is better, they just do different things.

    std::remove is more generally useful, and that is why it is more often seen; in particular, std::remove followed by vector::erase does nothing when the element is not present in the vector, while std::find followed by vector::erase has undefined behavior.

    Note that both "find-erase", "remove-erase" maintain the relative order of the elements. If you want to remove an element from the vector but do not care about the resulting order of the elements, you can use "find-move-pop_back" or "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());
    
    0 讨论(0)
提交回复
热议问题