我的版本如下,我只适用erase
毕竟向量中的元素vSource
已移至最后std::remove
并跟踪指向向量末尾的指针vDestination
不要无缘无故地迭代它。
void remove_elements(vector<int>& vDestination, const vector<int>& vSource)
{
auto last = std::end(vDestination);
std::for_each(std::begin(vSource), std::end(vSource), [&](const int & val) {
last = std::remove(std::begin(vDestination), last, val);
});
vDestination.erase(last, std::end(vDestination));
}
参见 coliru :http://coliru.stacked-crooked.com/a/6e86893babb6759c http://coliru.stacked-crooked.com/a/6e86893babb6759c
Update
这是一个模板版本,因此您不必关心容器类型:
template <class ContainerA, class ContainerB>
void remove_elements(ContainerA & vDestination, const ContainerB & vSource)
{
auto last = std::end(vDestination);
std::for_each(std::begin(vSource), std::end(vSource), [&](typename ContainerB::const_reference val) {
last = std::remove(std::begin(vDestination), last, val);
});
vDestination.erase(last, std::end(vDestination));
}
Note
此版本适用于没有任何限制的向量,如果您的向量已排序,您可以采取一些快捷方式并避免一遍又一遍地迭代向量以删除每个元素。