This is a Set ADT and I am having problems with overloading the + operator to do a union of two sets. What I was trying to do was load two vectors of integers to a temporary vector (removing the duplicates) but I have been unable to get it to work. Any suggestions please? Thanks.
Code:
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std ;
class Set
{
public:
void add (int anItem) ;
void remove (int anItem) ;
int size () ;
bool is_empty () ;
bool has (int& the_target_item) ;
friend ostream& operator << (ostream& OUTPUT, Set& aSet) ;
friend istream& operator >> (istream& INPUT, Set& aSet) ;
friend Set& operator + (Set& aSet, Set& anotherSet) ;
private:
vector <int> theItems ;
};
int main ()
{
system ("Pause") ;
return 0 ;
}
void Set :: add (int anItem)
{
if (Set :: has(anItem))
{
//no-op
}
else
{
theItems . push_back (anItem) ;
}
}
void Set :: remove (int anItem)
{
for (int i = Set :: has (anItem); i < theItems . size () - 1; i++)
{
theItems[i] = theItems[i+1] ;
}
theItems . pop_back () ;
}
ostream& operator << (ostream& OUTPUT, Set& aSet)
{
OUTPUT << "Current Size: " << aSet . theItems . size() << " " << endl ;
for (int i=0; i < aSet . theItems . size(); i++)
{
OUTPUT << aSet . theItems[i] << " " ;
}
OUTPUT << endl ;
return OUTPUT ;
}
istream& operator >> (istream& INPUT, Set& aSet)
{
int anItem ;
cout << "Enter Items (Ctrl-z to End): " ;
while ( cin >> anItem)
{
aSet . add (anItem) ;
}
return INPUT ;
}
int Set :: size ()
{
return theItems . size () ;
}
Set operator + (Set aSet, Set anotherSet)
{
vector <int> tmpVector ;
tmpVector . push_back (aSet) ;
tmpVector . push_back (anotherSet) ;
}
bool Set :: is_empty ()
{
if (theItems . size () == 0)
{
return true ;
}
else
{
return false ;
}
}
bool Set :: has (int& the_target_item)
{
int i = 0 ;
while ( i < theItems . size () && theItems [i] != the_target_item)
{
i++ ;
}
if ( i == theItems.size ( ) )
{
return false ;
}
else
{
return true ;
}
}