CPP   31

IntBag.h

Guest on 5th August 2022 01:30:26 AM

  1. class IntBag {
  2.  
  3. private:
  4.  
  5.   enum { MAXVALUES = 10 };
  6.  
  7.   int data [MAXVALUES];
  8.   int count;  // number of values currently in the bag
  9.  
  10.   bool walkInProgress;
  11.   int walkPosition; // position of last value returned
  12.  
  13. public:
  14.  
  15.   // constructs an empty bag.
  16.   // for really trivial constructors and methods, the complete
  17.   // implementation is often placed directly in the class definition.
  18.   IntBag () { count = 0; walkInProgress = false; }
  19.  
  20.   // adds a value to the bag.  returns true on success (space available)
  21.   // and false on failure (bag full)
  22.   bool add (int value);
  23.  
  24.   // removes one occurrence of the specified value from the bag.  returns
  25.   // true on success (value existed) and false on failure (value did not exist)
  26.   bool remove (int value);
  27.  
  28.   // returns the number of times that the specified value occurs in the bag
  29.   int countOccurrences (int value) const;
  30.  
  31.   // returns the number of values in the bag.
  32.   int size () const { return count; }
  33.  
  34.   // These two methods make it possible to "walk through" the values in a
  35.   // bag.  The values in the bag may be returned in any order.  There is no
  36.   // guarantee that they will be returned in numerical order, in the order in
  37.   // which they were entered, or any other particular order.  "startWalk" may
  38.   // be called at any time.  If returns true on success (value obtained) and
  39.   // false on failure (bag empty).  "continueWalk" may only be called if
  40.   //       1/. the bag has not been modified since a walk was
  41.   //           begun by calling startWalk AND
  42.   //       2/. the last call to startWalk or ContinueWalk returned true
  43.   // If these conditions are not met, "continueWalk" throws a "range_error"
  44.   // exception.  It returns true on success (value obtained) and false on
  45.   // failure (no more values).
  46.   bool startWalk (int &value);
  47.   bool continueWalk (int &value);
  48.  
  49.   // randomly picks and returns one of the values in the bag.
  50.   // throws a range_error exception if the bag is empty.
  51.   int pickRandom () const;
  52.  
  53. };

Raw Paste


Login or Register to edit or fork this paste. It's free.