home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / VSCPPv8.zip / VACPP / IBMCPP / samples / IOC / SUMUP / SUMUP.CPP < prev    next >
Text File  |  1995-03-15  |  2KB  |  66 lines

  1. /*************************************************************************
  2.   IBM C/C++ Tools Version 3.00 - Collection Class Library
  3.  (C) Copyright IBM Corporation 1992 ,1995, Licensed Program-Property of
  4.  IBM.  All Rights Reserved.  US Government Users Restricted Rights - Use,
  5.  duplication or disclosure restricted by GSA ADP Schedule Contract with
  6.  IBM Corp.
  7.  *************************************************************************/
  8.  
  9. /*-------------------------------------------------------------*\
  10. |  sumup.CPP  - Sum up integers to demonstrate using iterators. |
  11. |                                                    """""""""  |
  12. |  Add all elements in a bag to demonstrate the use of          |
  13. |  iterators with additional arguments.                         |
  14. |  The bag elements are integers passed as arguments to main(). |
  15. \*-------------------------------------------------------------*/
  16.  
  17.    #include <ibag.h>
  18.    #include <iostream.h>
  19.  
  20.    typedef IBag < int > IntBag;
  21.  
  22.    class SumIterator : public IConstantIterator < int > {
  23.      int ivSum;
  24.    public:
  25.      SumIterator () : ivSum (0) {}
  26.      IBoolean applyTo (int const& i) {
  27.        ivSum += i;
  28.        return True;
  29.      }
  30.      int sum () { return ivSum; }
  31.    };
  32.  
  33.  
  34.    int sumUsingIteratorObject (IntBag const& bag) {
  35.      SumIterator sumUp;
  36.      bag.allElementsDo (sumUp);
  37.      return sumUp.sum ();
  38.    }
  39.  
  40.  
  41.    IBoolean sumUpFunction (int const& i, void* sum) {
  42.      *(int*)sum += i;
  43.      return True;
  44.    };
  45.  
  46.    int sumUsingIteratorFunction (IntBag const& bag) {
  47.      int sum = 0;
  48.      bag.allElementsDo (sumUpFunction, &sum);
  49.      return sum;
  50.    }
  51.  
  52.  
  53. int main (int argc, char* argv[])  {
  54.      IntBag intbag;
  55.      for (int cnt=1; cnt < argc; cnt++)
  56.         intbag.add(atoi(argv[cnt]));
  57.  
  58.      cout << "Sum obtained using an Iterator Object = "
  59.           <<  sumUsingIteratorObject(intbag)  << endl;
  60.  
  61.      cout << "Sum obtained using an Iterator Function = "
  62.           <<  sumUsingIteratorFunction(intbag)  << endl;
  63.  
  64.      return 0;
  65.      }
  66.