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] << " ";
}
}
This is a
O(nlogn)
method, which also remove duplicate elements. The key point is to take advantage of the ordering. Using two-pointer method can help make it.If the input is reliable(every element is unique in its own vector), you can omit the
vec.erase
line.