1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//======================================================================
template <class T> void myCompare( vector<T> A, vector<T> B, vector<T> &intersection, vector<T> &difference )
{
intersection.clear();
difference.clear();
vector<bool> usedA( A.size(), false ); // keep tabs on which elements of A and B have been used in intersection
vector<bool> usedB( B.size(), false );
for ( int i = 0; i < A.size(); i++ )
{
for ( int j = 0; j < B.size(); j++ )
{
if ( !usedB[j] && B[j] == A[i] ) // found a match: stick it in intersection, and mark both A and B elements
{
intersection.push_back( A[i] );
usedA[i] = true;
usedB[j] = true;
break; // breaks out of the search in B
}
}
}
for ( int i = 0; i < A.size(); i++ ) if ( !usedA[i] ) difference.push_back( A[i] );
for ( int j = 0; j < B.size(); j++ ) if ( !usedB[j] ) difference.push_back( B[j] );
}
//======================================================================
template <class T> void write( string s, vector<T> A )
{
cout << s;
for ( T x : A ) cout << x << " ";
cout << '\n';
}
//======================================================================
int main()
{
vector<int> A = { 1, 1, 1, 2, 2 };
vector<int> B = { 2, 1, 2, 1, 2 };
vector<int> intersection, difference;
myCompare( A, B, intersection, difference );
write( "Intersection: ", intersection );
write( "Difference: ", difference );
}
|