c++ - 如何有效地从给定另一个 vector 的 vector 中删除元素

标签 c++ algorithm c++11 vector

从给定另一个 vector 的 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

最佳答案

我的版本如下,我只申请了erase vector 中的所有元素 vSource已被std::remove移到最后并跟踪指向 vector 末尾的指针 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));
}

参见大肠杆菌:http://coliru.stacked-crooked.com/a/6e86893babb6759c


更新

这里是一个模板版本,所以你不用关心容器类型:

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));
}

注意

此版本适用于没有任何约束的 vector ,如果您的 vector 已排序,您可以采取一些快捷方式,避免反复迭代 vector 以删除每个元素。

关于c++ - 如何有效地从给定另一个 vector 的 vector 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39139341/

相关文章:

C++ - 带有 std::string 的统一初始值设定项

c++ - 发送固定长度的 header

c++ - 默认退出函数实现

c++ - 为什么malloc总是分配内存失败(大约9GB,但我有16GB物理内存)?

来自类的c++第二个函数无法访问第一个

algorithm - 可能的 sha1hash 结果范围是多少?

algorithm - 什么是协同算法?

algorithm - 如何将转置表与 MTD(f) 一起使用

c++ - 空嵌套元组错误

c++ - 在 constexpr GLenum 数组中存储 OpenGL 颜色附件