How would one find the difference between sets in C++ using Vector A and Vector B. I figured out the Union and Intersection but for some reason can not get the difference no matter what I try. Any help would be appreciated (BTW I need it to be done manually not using a built in method.)
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>
using namespace std;
void Difference();
int main()
{
Difference();
return 0;
}
void Difference()
{
int temp = 0;
vector<int> D{};
vector<int> A{3, 4, 9, 12, 13, 15};
vector<int> B{1, 3, 5, 7, 9};
for(int i = 0; i < A.size(); i++)
{
for (int j = 0; j < B.size(); j++)
{
if (A[i] != B[j])
{
int temp = A[i];
D.push_back(temp);
}
//Used To Sort The Vector So There Is No Duplicates And Its In Order!
sort( D.begin(), D.end() );
D.erase( unique( D.begin(), D.end() ), D.end() );
}
}
cout << "Difference: ";
for(int z = 0; z < D.size(); z++)
{
cout << D[z] << " ";
}
}
You should realise that this will add
A[i]to the vectorDfor every single element ofBthatA[i]is not equal to. So, unlessBconsists only of identical elements, everything inAwill make it across toD. In more detail, the operation{3, 4, 9} - {1, 3}will:3once (because it's not equal to1);4twice (because it's equal to neither1nor3); and9twice (because it's equal to neither1nor3).Hence, after duplicate removal, you'll end up with
{3, 4, 9}despite the fact the3is in both vectors.What you need to do is check if any element matches, not every element as your current code does. That could be done with the following loop:
That way, you also don't have to worry about duplicate removal, unless there are duplicates in the original vectors. If that's the case, you'll probably need some more intelligence in your original algorithm (and this one) to handle the difference between (for example)
{1, 2, 3, 3, 3}and{3}. In other words, should that be{1, 2}or{1, 2, 3, 3}?