Radoslav Pavlov
Radoslav Pavlov

Reputation: 29

c++ find different elements from two vectors using set_intersection?

So i got 2 vectors. I want to find the different elements from both vectors. Example:

2 5 4 6

2 4 3

Output would be 5 3 6 -> digits that appear in only one of the vectors. This is my attempt so far:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

std::vector<int> intersection(std::vector<int> &v1,
                                      std::vector<int> &v2){
   std::vector<int> v3;

   std::sort(v1.begin(), v1.end());
   std::sort(v2.begin(), v2.end());

   std::set_intersection(v1.begin(),v1.end(),
                         v2.begin(),v2.end(),
                         back_inserter(v3));
   return v3;
}

int main(){
    int a,b;
    int digit = 0;
    vector<int> v1;
    vector<int> v2;
    cin >> a >> b;
   
    for ( int i = 0; i < a; i++ ){ 
       cin >> digit;
       v1.push_back( digit );
    }
    for ( int i = 0; i < b; i++ ){ 
       cin >> digit;
       v2.push_back( digit );
    }
    auto res = intersection(v1, v2);
   
    for(int n : res)
       std::cout << n << ' ';
    }

    return 0;
}

This currently returns the common elements from those vectors. Is there a way to reverse this and return the not common elements?

Upvotes: 0

Views: 1237

Answers (1)

Deepak Tatyaji Ahire
Deepak Tatyaji Ahire

Reputation: 5321

Credits to @Blastfurnace.

Use std::set_symmetric_difference as follows:

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

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

    std::vector<int> v_symDifference;

    std::set_symmetric_difference(
        v1.begin(), v1.end(),
        v2.begin(), v2.end(),
        std::back_inserter(v_symDifference));

    for(int n : v_symDifference)
        std::cout << n << ' ';
}

Output:

3 5 6 

Upvotes: 1

Related Questions