home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C21 / CalcInventory.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  970 b   |  39 lines

  1. //: C21:CalcInventory.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // More use of for_each()
  7. #include "Inventory.h"
  8. #include "PrintSequence.h"
  9. #include <vector>
  10. #include <algorithm>
  11. using namespace std;
  12.  
  13. // To calculate inventory totals:
  14. class InvAccum {
  15.   int quantity;
  16.   int value;
  17. public:
  18.   InvAccum() : quantity(0), value(0) {}
  19.   void operator()(const Inventory& inv) {
  20.     quantity += inv.getQuantity();
  21.     value += inv.getQuantity() * inv.getValue();
  22.   }
  23.   friend ostream& 
  24.   operator<<(ostream& os, const InvAccum& ia) {
  25.     return os << "total quantity: " 
  26.       << ia.quantity
  27.       << ", total value: " << ia.value;
  28.   }
  29. };
  30.  
  31. int main() {
  32.   vector<Inventory> vi;
  33.   generate_n(back_inserter(vi), 15, InvenGen());
  34.   print(vi, "vi");
  35.   InvAccum ia = for_each(vi.begin(),vi.end(),
  36.     InvAccum());
  37.   cout << ia << endl;
  38. } ///:~
  39.