/* IntegerSet.cpp * Represents a set of integers from 1 - CAP inclusive. * Anthony Larrain * Spring 2006, csc309 */ #include #include #include #include using namespace std; const int CAP = 101; class IntegerSet { private: bool elements [CAP]; int cardinality; bool isValid(int e); public: IntegerSet(); int size(); bool add(int e); bool contains(int e); string toString(); // This method is basically worthless as we will see next week. // I put it in here to help with the homework. IntegerSet clone(); }; int main() { IntegerSet set1; set1.add(4); set1.add(8); set1.add(11); cout << "Number of Elements in the set are " << set1.size() << endl; cout << set1.contains(4) << endl; cout << set1.contains(200) << endl; cout << set1.contains(2) << endl << endl;; IntegerSet set2(set1); IntegerSet set3 = set1.clone(); cout << "Set 1 is " << set1.toString() << endl; cout << "Set 2 is " << set2.toString() << endl << "Set 3 is " << set3.toString() << endl << endl << endl; set2.add(100); cout << "Set 1 is " << set1.toString() << endl << "Set 2 is " << set2.toString() << endl << "Set 3 is " << set3.toString() << endl << endl << endl; set3 = set2; cout << "Set 1 is " << set1.toString() << endl << "Set 2 is " << set2.toString() << endl << "Set 3 is " << set3.toString() << endl << endl << endl; set3.add(50); cout << "Set 1 is " << set1.toString() << endl << "Set 2 is " << set2.toString() << endl << "Set 3 is " << set3.toString() << endl; system("PAUSE"); return EXIT_SUCCESS; } IntegerSet::IntegerSet(){ cardinality = 0; for(int i = 0; i < CAP; ++i){ elements[i] = false; } } bool IntegerSet::add(int e){ if(!isValid(e)){ return false; } else if (elements[e]){ return false; } ++cardinality; return elements[e] = true; } int IntegerSet::size(){ return cardinality; } bool IntegerSet::contains(int e){ if(!isValid(e)){ return false; } return elements[e]; } string IntegerSet::toString(){ ostringstream st; for(int i = 1; i < CAP; i++){ if(elements[i]){ st << i << ' '; } } return st.str(); } IntegerSet IntegerSet::clone(){ IntegerSet set; for(int i = 1; i < CAP; ++i){ if(elements[i]){ set.add(i); } } return set; } bool IntegerSet::isValid(int e){ return (e > 0 && e < CAP); }