如何有效地从给定另一个向量的向量中删除元素 [英] How to efficiently delete elements from a vector given an another vector
问题描述
在给定另一个向量的向量中删除元素的最好方法是什么?
What is the best way to delete elements from a vector given an another vector?
我想出了以下代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void remove_elements(vector<int>& vDestination, const vector<int>& vSource)
{
if(!vDestination.empty() && !vSource.empty())
{
for(auto i: vSource) {
vDestination.erase(std::remove(vDestination.begin(), vDestination.end(), i), vDestination.end());
}
}
}
int main()
{
vector<int> v1={1,2,3};
vector<int> v2={4,5,6};
vector<int> v3={1,2,3,4,5,6,7,8,9};
remove_elements(v3,v1);
remove_elements(v3,v2);
for(auto i:v3)
cout << i << endl;
return 0;
}
这里的输出将是:
7
8
9
推荐答案
我的版本如下,我只应用擦除
已移动到
std :: remove
的末尾,并跟踪指向向量结尾的指针 vDestination
不对其进行迭代。
My version is the following, I only apply erase
after all elements from the vector vSource
have been moved to the end by std::remove
and keep track of the pointer to the end of the vector vDestination
to not iterate over it for nothing.
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
更新
这里是一个模板版本,所以你不关心容器类型:
Here is a template version, so you don't care about the container type :
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));
}
/ strong>
Note
此版本适用于没有任何约束的向量,如果你的向量被排序,你可以采取一些快捷方式,避免迭代遍历向量删除每个元素。
This version works for vectors without any constraints, if your vectors are sorted you can take some shortcuts and avoid iterating over and over the vector to delete each element.
这篇关于如何有效地从给定另一个向量的向量中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!