// #ifndef _BAG_ #define _BAG_ typedef int bag_type; class Bag { private: int count; // members in bag bag_type data[20]; // data store up to 20 members public: Bag(); // Constructor bool insert(bag_type); // Put a member in the bag bool remove(bag_type); // remove a member from the bag int size(); // number of members in bag void clear(); // remove all members from bag bool inbag(bag_type); // is a member in the bag? int howmany(bag_type); // how many member in bag. }; #endif
#include "bag.h" #include <iostream> Bag::Bag() // Constructor { // set the initial state of the bag count=0; } void Bag::clear() // Clear the bag { count=0; } bool Bag::insert(bag_type value) //Place a value in Bag { bool reply; if(count <20 ) { data[count]=value; reply=true; count++; } else { reply=false; } return reply; } bool Bag::inbag(bag_type value) // Is a value in the bag? { bool reply=false; int index; for(index=0;index<count&& !reply;index++) if(data[index] == value) reply=true; return reply; } int Bag::howmany(bag_type value) //How many of element; { int thismany=0; int index; for(index=0;index<count;index++) if(data[index]==value) thismany++; return thismany; }
bool Bag::remove(bag_type value) // Remove a value { bool reply=false; int index; if(howmany(value) == 0) return reply; reply=true; index=0; while(data[index] != value) index++; for(;index<count;index++) data[index]=data[index+1]; count--; } int Bag::size() // How many elements in bag? { return count; }
#include <iostream> #include <cstdlib> #include "bag.h" using namespace std; int main(int argc, char *argv[]) { Bag b; bag_type value; cout << "Bag" << endl; b.insert(4); do { value=rand()%6 +1; } while(b.insert(value)); cout << b.size()<< " elements in the bag" << endl; cout << b.howmany(4) << " fours " << endl; b.remove(4); cout << b.size()<< " elements in the bag" << endl; cout << b.howmany(4) << " fours " << endl; cout << b.howmany(5) << " fives " << endl; while(b.inbag(5)) b.remove(5); cout << b.howmany(5) << " fives " << endl; system("Pause"); return 0; }