Richard Wieditz
Richard Wieditz

Reputation: 446

C++ get the difference between two vectors

imagine you got 2 vectors:

vector<int> ar1, a2;

ar1 = {1,1,2,3,3,4,5,5,6};
ar2 = {1,2,3,4,5,6};

how to do something like this in a good way (using C++) ?

b = ar1 - ar2
// b = {1,3,5}

Upvotes: 16

Views: 34607

Answers (2)

Donald Duck
Donald Duck

Reputation: 8882

The accepted answer only works if you have sorted vectors of a type for which the < operator is overloaded.

If you have a type for which the < operator is overloaded but the vectors aren't sorted, you need to sort them first:

#include <algorithm>
#include <vector>

std::vector<int> v1 {3,1,3,2,4,1,5,5,6};
std::vector<int> v2 {6,1,4,5,2,3};
std::vector<int> diff;
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::inserter(diff, diff.begin()));

If the < operator isn't overloaded, you can write your own comparator:

#include <algorithm>
#include <vector>

std::vector<SomeType> v1 {...};
std::vector<SomeType> v2 {...};
std::vector<SomeType> diff;
const auto cmp = [](const SomeType &a, const SomeType &b){
    //Should return true if a is considered strictly less than b
};
std::sort(v1.begin(), v1.end(), cmp);
std::sort(v2.begin(), v2.end(), cmp);
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::inserter(diff, diff.begin()), cmp);

However, if writing your own comparator is not trivial, it might be easier to simply write your own function to find the difference between the vectors:

#include <algorithm>
#include <vector>

template<typename T>
std::vector<T> vectorDifference(const std::vector<T> &v1, const std::vector<T> &v2){
    //Make the result initially equal to v1
    std::vector<T> result = v1;

    //Remove the elements in v2 from the result
    for(const T &element: v2){
        const auto it = std::find(result.begin(), result.end(), element);
        if(it != result.end()){
            result.erase(it);
        }
    }
    return result;
}

Upvotes: 0

George Newton
George Newton

Reputation: 827

//from cppreference
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
 
int main() {
 
    std::vector<int> v1 {1,1,2,3,3,4,5,5,6};
    std::vector<int> v2 {1,2,3,4,5,6};
    std::vector<int> diff;
    //no need to sort since it's already sorted
    //but you can sort with:
    //std::sort(std::begin(v1), std::end(v1))

    std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(),
        std::inserter(diff, diff.begin()));
 
    for (auto i : v1) std::cout << i << ' ';
    std::cout << "minus ";
    for (auto i : v2) std::cout << i << ' ';
    std::cout << "is: ";
 
    for (auto i : diff) std::cout << i << ' ';
    std::cout << '\n';
}

Upvotes: 65

Related Questions