Chapter 22. Mastering STL Algorithms and Function Objects

As you read in Chapter 21, the STL provides an impressive collection of generic data structures. Most libraries stop there. The STL, however, contains an additional assortment of generic algorithms that can, with some exceptions, be applied to elements from any container. Using these algorithms, you can find elements in containers, sort elements in containers, process elements in containers, and perform a whole host of other operations. The beauty of the algorithms is that they are independent not only of the types of the underlying elements, but of the types of the containers on which they operate. Algorithms perform their work using only the iterator interfaces.

Many of the algorithms accept callbacks: a function pointer or something that behaves like a function pointer, such as an object with an overloaded operator(). Conveniently, the STL provides a set of classes that can be used to create callback objects for the algorithms. These callback objects are called function objects, or just functors.

This chapter includes:

  • An overview of the algorithms and three sample algorithms: find(), find_if(), and accumulate()

  • A detailed look at function objects

    • Predefined function object classes: arithmetic function objects, comparison function objects, and logical function objects

    • Function object adapters

    • How to write your own function objects

  • The details of the STL algorithms

    • The utility algorithms

    • The nonmodifying algorithms: search, numerical ...

Get Professional C++ now with O’Reilly online learning.

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