home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
OS/2 Shareware BBS: 10 Tools
/
10-Tools.zip
/
cset21v1.zip
/
IBMCPP
/
SAMPLES
/
ICLCC
/
SUMUP.C
< prev
next >
Wrap
C/C++ Source or Header
|
1993-05-07
|
3KB
|
75 lines
/******************************************************************************/
/* */
/* COPYRIGHT: */
/* ---------- */
/* Copyright (C) International Business Machines Corp., 1991,1992. */
/* */
/* DISCLAIMER OF WARRANTIES: */
/* ------------------------- */
/* The following [enclosed] code is sample code created by IBM */
/* Corporation. This sample code is not part of any standard IBM product */
/* and is provided to you solely for the purpose of assisting you in the */
/* development of your applications. The code is provided "AS IS", */
/* without warranty of any kind. IBM shall not be liable for any damages */
/* arising out of your use of the sample code, even if they have been */
/* advised of the possibility of such damages. */
/* */
/******************************************************************************/
/*-------------------------------------------------------------*\
| sumup.C - 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) {}
Boolean 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 ();
}
Boolean 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) << "\n";
cout << "Sum obtained using an Iterator Function = "
<< sumUsingIteratorFunction(intbag) << "\n";
return 0;
}