Online Book Reader

Home Category

Professional C__ - Marc Gregoire [222]

By Root 1458 0
in order to search all the elements of the vector. If you want to search in a sub range, you can change the first argument to the find() method and the value of the end iterator.

Here is a sample run of the program:

Enter a number to add (0 to stop): 3

Enter a number to add (0 to stop): 4

Enter a number to add (0 to stop): 5

Enter a number to add (0 to stop): 6

Enter a number to add (0 to stop): 0

Enter a number to lookup (0 to stop): 5

Found 5

Enter a number to lookup (0 to stop): 8

Could not find 8

Enter a number to lookup (0 to stop): 4

Found 4

Enter a number to lookup (0 to stop): 2

Could not find 2

Enter a number to lookup (0 to stop): 0

Some containers, such as map and set, provide their own versions of find() as class methods.

If a container provides a method with the same functionality as a generic algorithm, you should use the method instead, because it’s faster. For example, the generic find() algorithm runs in linear time, even on a map iterator, while the find() method on a map runs in logarithmic time.

find_if() is similar to find(), except that it accepts a predicate function callback instead of a simple element to match. A predicate returns true or false. The find_if() algorithm calls the predicate on each element in the range until the predicate returns true, in which case find_if()returns an iterator referring to that element. The following program reads test scores from the user, then checks if any of the scores are “perfect.” A perfect score is a score of 100 or higher. The program is similar to the previous example. Only the differences are highlighted.

bool perfectScore(int num)

{

return (num >= 100);

}

int main()

{

int num;

vector myVector;

while (true) {

cout << "Enter a test score to add (0 to stop): ";

cin >> num;

if (num == 0) {

break;

}

myVector.push_back(num);

}

auto end = myVector.end();

auto it = find_if(myVector.begin(), end, perfectScore);

if (it == end) {

cout << "No perfect scores" << endl;

} else {

cout << "Found a \"perfect\" score of " << *it << endl;

}

return 0;

}

Code snippet from AlgorithmOverview\FindIf.cpp

This program passes a pointer to the perfectScore() function, which the find_if() algorithm then calls on each element until it returns true.

Here is the same example but using a C++11 lambda expression. It gives you an initial idea about the power of lambda expressions. Don’t worry about their syntax. They are explained in detail later in this chapter. Note the absence of the perfectScore() function.

int num;

vector myVector;

while (true) {

cout << "Enter a test score to add (0 to stop): ";

cin >> num;

if (num == 0) {

break;

}

myVector.push_back(num);

}

auto end = myVector.end();

auto it = find_if(myVector.begin(), end, [](int i){ return i >= 100; });

if (it == end) {

cout << "No perfect scores" << endl;

} else {

cout << "Found a \"perfect\" score of " << *it << endl;

}

Code snippet from AlgorithmOverview\FindIfLambda.cpp

Unfortunately, the STL provides no find_all() or equivalent algorithm that returns all instances matching a predicate. Chapter 17 shows you how to write your own find_all() algorithm.

The accumulate Algorithms

It’s often useful to calculate the sum, or some other arithmetic quantity, of all the elements in a container. The accumulate() function does just that. In its most basic form, it calculates the sum of the elements in a specified range. For example, the following function calculates the arithmetic mean of a sequence of integers in a vector. The arithmetic mean is simply the sum of all the elements divided by the number of elements.

#include

#include

using namespace std;

double arithmeticMean(const vector& nums)

{

double sum = accumulate(nums.begin(), nums.end(), 0);

return sum / nums.size();

}

Code snippet from AlgorithmOverview\Accumulate.cpp

Note that accumulate() is declared in , not in . The accumulate() algorithm takes as its third parameter an initial value for the sum, which in this case should be 0 (the identity

Return Main Page Previous Page Next Page

®Online Book Reader