// Joe Shinnerl (shinnerl@ucla.edu), CS 31 // Example: simple sets of integers // // To do: // Set(int data0[], size0); // Initializing constructor. // friend Set setUnion(const Set&, const Set&); // // Note: No need for Set(const Set& ); the "automatic" Copy Constructor is OK! #include #include using namespace std; class Set{ public: Set() : size(0) {} // Default constructor. Set(int data0[], int size0); // Initializing constructor. bool has( int ) const; // membership checker void join( int ); // membership maker -- union with one more int. void assign( const Set& ); // assignment friend Set setIntersect(const Set&, const Set&); friend Set setUnion(const Set&, const Set&); void get( istream& ); // stream input void put( ostream& ) const; // stream output private: static const int MAX_SIZE = 20; int data[ MAX_SIZE ]; int size; }; bool Set::has( int value ) const { bool answer = false; for (int i=0; i< size && !answer; ++i) if (data[i] == value ) answer = true; return answer; } void Set::join( int value ) { // Corrected 10:15am 2/20/03 if ( size < MAX_SIZE ){ if ( !has(value) ) data[size++] = value ; } else cerr << "Error in Set::join(): " << "storage size limit exceeded.\n"; } void Set::assign( const Set& rhs ){ // assignment size = rhs.size; for (int i = 0; i < size; ++i) data[i] = rhs.data[i]; } void Set::get( istream& is ){ is >> size; if ( size > 0 && size <= MAX_SIZE ){ for (int i = 0; i < size; ++i) is >> data[i]; } else cerr << "Set::get() input error: set size out of range.\n"; } void Set::put( ostream& os ) const { // Note: not symmetric w.r.t. get(). for (int i = 0; i < size; ++i) os << data[i] << " "; } Set setIntersect(const Set& A, const Set& B){ // Quadratic-time solution for unsorted sets Set C; for (int i = 0; i < A.size; ++i) if (B.has( A.data[i] )) C.join( A.data[i] ); return C; } void menu(){ cout << "Enter \n" << " E to ENTER set A or set B by keyboard input \n" << " V to VIEW all sets \n" << " R to REPLACE a set \n" << " I to find the INTERSECTION of A and B \n" << " U to find the UNION of A and B \n" << " Q to QUIT \n" << endl; } void prompt() { cout << "\nEVRIUQ > "; } int main(){ Set A,B,C; menu(); char ch; do{ prompt(); cin >> ch; switch (ch){ case 'e': case 'E': { cout << "A or B? "; cin >> ch; if (ch == 'A') A.get(cin); else if (ch == 'B') B.get(cin); break; } case 'v': case 'V': cout << " A = "; A.put(cout); cout << endl; cout << " B = "; B.put(cout); cout << endl; cout << " C = "; C.put(cout); cout << endl; case 'i': case 'I': C.assign( setIntersect(A, B) ); } } while (ch != 'q' && ch != 'Q' ); return 0; }