从“查找"或“删除"中使用迭代器擦除 [英] Erasing using iterator from 'find' or 'remove'
问题描述
我想知道在C ++中从向量中删除元素的最佳实践是什么.
I would like to know what's the best practice to remove an element from a vector in C++.
我见过很多人使用std :: remove查找和删除元素,然后使用擦除从矢量中删除元素.
I have seen many times people using std::remove to find and delete the element, and then using erase to remove the element from the vector.
但是,为什么它比使用find获得要删除的元素的迭代器,然后将擦除与该迭代器一起使用要好呢?
But why is it better than using find to get the iterator of the element you want to remove and then using the erase with that iterator?
谢谢
推荐答案
std :: find
后跟 vector :: erase
将使用以下命令擦除对象的首次出现来自 vector
的给定值.
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
后跟 vector :: erase
将从中删除具有给定值的对象的每次出现向量
.
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
通常更有用,这就是为什么它更常见的原因;特别是,当向量中不存在元素时, std :: remove
后跟 vector :: erase
不会执行任何操作,而 std :: find
后跟 vector :: erase
具有未定义的行为.
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.
请注意,查找擦除"和删除擦除"都保持元素的相对顺序.如果要从向量中删除元素,但不关心元素的结果顺序,则可以使用"find-move-pop_back"或"partition-erase":
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());
这篇关于从“查找"或“删除"中使用迭代器擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!