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 >
Wrap
Text File
|
1995-03-15
|
2KB
|
66 lines
/*************************************************************************
IBM C/C++ Tools Version 3.00 - Collection Class Library
(C) Copyright IBM Corporation 1992 ,1995, Licensed Program-Property of
IBM. All Rights Reserved. US Government Users Restricted Rights - Use,
duplication or disclosure restricted by GSA ADP Schedule Contract with
IBM Corp.
*************************************************************************/
/*-------------------------------------------------------------*\
| sumup.CPP - Sum up integers to demonstrate using iterators. |
| """"""""" |
| Add all elements in a bag to demonstrate the use of |
| iterators with additional arguments. |
| The bag elements are integers passed as arguments to main(). |
\*-------------------------------------------------------------*/
#include <ibag.h>
#include <iostream.h>
typedef IBag < int > IntBag;
class SumIterator : public IConstantIterator < int > {
int ivSum;
public:
SumIterator () : ivSum (0) {}
IBoolean applyTo (int const& i) {
ivSum += i;
return True;
}
int sum () { return ivSum; }
};
int sumUsingIteratorObject (IntBag const& bag) {
SumIterator sumUp;
bag.allElementsDo (sumUp);
return sumUp.sum ();
}
IBoolean sumUpFunction (int const& i, void* sum) {
*(int*)sum += i;
return True;
};
int sumUsingIteratorFunction (IntBag const& bag) {
int sum = 0;
bag.allElementsDo (sumUpFunction, &sum);
return sum;
}
int main (int argc, char* argv[]) {
IntBag intbag;
for (int cnt=1; cnt < argc; cnt++)
intbag.add(atoi(argv[cnt]));
cout << "Sum obtained using an Iterator Object = "
<< sumUsingIteratorObject(intbag) << endl;
cout << "Sum obtained using an Iterator Function = "
<< sumUsingIteratorFunction(intbag) << endl;
return 0;
}