Scalar-producing algorithms, Reduce sequence to a single value, Count the number of elements that satisfy a – HP Integrity NonStop H-Series User Manual

Page 169: Condition, Chapter 13, Reduce, Sequence to a single value, Count the number of elements, Scalar generating algorithms

Advertising
background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Scalar-Producing Algorithms

Obtaining the Source

The next category of algorithms are those that reduce an entire sequence to a single scalar value.

Remember that two of these algorithms, accumulate() and inner_product(), are declared in the numeric header file, not the
algorithm header file as are the other generic algorithms.

Count the Number of Elements that Satisfy a Condition

The algorithms count() and count_if() are used to discover the number of elements that match a given value or that satisfy a
given predicate, respectively. Both take as argument a reference to a counting value (typically an integer), and increment
this value. Note that the count is passed as a by-reference argument, and is not returned as the value of the function. The
count() function itself yields no value.

void count (InputIterator first, InputIterator last,
const T&, Size &);
void count_if (InputIterator first, InputIterator last,
Predicate, Size &);

The Resulting Count

The example code fragment illustrates the use of these algorithms. The call on count() will count the number of occurrences
of the letter e in a sample string, while the invocation of count_if() will count the number of vowels.

void count_example ()
// illustrate the use of the count algorithm
{
int eCount = 0;
int vowelCount = 0;
char * text = "Now is the time to begin";

count (text, text + strlen(text), 'e', eCount);
count_if (text, text + strlen(text), isVowel, vowelCount);

cout << "There are " << eCount << " letter e's " << endl
<< "and " << vowelCount << " vowels in the text:"
<< text << endl;
}

Reduce Sequence to a Single Value

The result generated by the accumulate() algorithm is the value produced by placing a binary operator between each
element of a sequence, and evaluating the result. By default the operator is the addition operator, +, however this can be
replaced by any binary function. An initial value (an identity) must be provided. This value is returned for empty sequences,
and is otherwise used as the left argument for the first calculation.

ContainerType accumulate (InputIterator first, InputIterator last,
ContainerType initial [, BinaryFunction ] );

The example program illustrates the use of accumulate() to produce the sum and product of a vector of integer values. In the

Advertising
This manual is related to the following products: