The How of Function Pointers, Functors, and Lambdas

Let’s look at an example using three approaches for passing information to an STL algorithm: function pointers, functors, and lambdas. (For convenience, we’ll refer to these three forms as function objects so that we won’t have to keep repeating “function pointer or functor or lambda.”) Suppose you wish to generate a list of random integers and determine how many of them are divisible by 3 and how many are divisible by 13. If necessary, imagine that this is a quest you find absolutely fascinating.

Generating the list is pretty straightforward. One option is to use a vector<int> array to hold the numbers and use the STL generate() algorithm to stock the array with random numbers:

#include <vector> ...

Get C++ Primer Plus now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.