#include // STL list container class (includes bool type) template class gen_bag{ // "adaptor" for S class to make a bag of floats. // The S class must provide the following member functions // a constructor with an integer argument, the optional size of the bag // a destructor that removes all memory allocated by members of S // bool attach(float) that "adds" an element to S // float detach(void) that "removes" and returns an element from S // void reset(void) that "empties" S so that 0 elements are attached // Note: attach and detach process the elements in unknown order // (which can be favorable to the internals of class S) int n; // number of elements in bag S *obj; // data structure containing elements public: gen_bag(unsigned int max_size = 0) {obj = new S(max_size); n = 0;}; ~gen_bag(void) {delete obj;} bool put_in(float x){bool flag = obj->attach(x); if(flag){n++; return true;} else return false;} // enters x into bag; duplicates are accepted; // returns true if the function was successful; // returns false otherwise (e.g., if the bag was full) float take_out(void){if(!is_empty()) {n--; return obj->detach();} else return 0.0; // no el's in bag } // returns an arbitrary element from the bag and // removes that single element int is_empty(void) {return n < 1; } void make_empty(void) {obj->reset(); n = 0;} // does not delete obj, just resets obj to empty friend class S; };// end gen_bag class array_bag{ float* arr;// array of elements int p; // position of last element int size; // size of array public: array_bag(unsigned int max_size) {p = 0; size = max_size; arr = new float[max_size];} ~array_bag(void){delete[] arr;} void reset(void){p = 0;} bool attach(float x) {if(p >= size) return false; arr[p++] = x; return true;} float detach(void) {return arr[--p];} };// end array_bag class list_bag{ list lst; public: list_bag(unsigned int max_size) {} void reset(void) {lst.erase(lst.begin(), lst.end()); } bool attach(float x){list::iterator p = lst.insert(lst.end(), x); if(p == lst.end()) return false; else return true;} float detach(void){float x = *(lst.begin()); lst.erase(lst.begin()); return x;} };// end list_bag #include int main(void) {gen_bag B(10); B.put_in(5.5); B.put_in(6.6); cout << B.take_out() <<" "<< B.take_out() << endl; B.make_empty(); B.put_in(7.7); gen_bag C(10); C.put_in(-5.5); C.put_in(-6.6); cout << C.take_out() <<" "<< C.take_out() << endl; C.make_empty(); C.put_in(-7.7); }