Delete elements of vector from other vector

Viewed 104

I want to delete all elements of a vector v which are contained by v2;

Is this solution good or should I use something else ?

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    std::vector<int> v = {1,2,3,4,5,1,2};
    std::vector<int> v2 = {1,2,3};
    
    v.erase(std::remove_if(v.begin(), v.end(), [v2](int x)
    {   
        auto it = std::find(v2.begin(), v2.end(), x);
        return it != v2.end();  
    }), v.end());
    
    for (auto i : v)
    {
        std::cout<<i<< " ";
    }

    return 0;
}

Output:

4 5
1 Answers

It's quite good for small filtering v2. It is a bit better if you pass v2 by reference.

v.erase(std::remove_if(v.begin(), v.end(), [&v2](int x)
{   
    std::find(v2.begin(), v2.end(), x) != v2.end();  
}), v.end());

If v2 is large it is better to replace it with std::unordered_set<int> s. It also removed duplicates in v2.

#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_set>

using namespace std;

int main()
{
    std::vector<int> v = {1,2,3,4,5,1,2};
    std::vector<int> v2 = {1,2,3};
    std::unordered_set<int> s(v2.begin(), v2.end());
    
    v.erase(std::remove_if(v.begin(), v.end(), [&s](int x) { return s.count(x); }),
            v.end());
    
    for (auto i : v)
    {
        std::cout<<i<< " ";
    }

    return 0;
}
Related