14.8.1. Lambdas Are Function Objects

In the previous section, we used a PrintString object as an argument in a call to for_each. This usage is similar to the programs we wrote in § 10.3.2 (p. 388) that used lambda expressions. When we write a lambda, the compiler translates that expression into an unnamed object of an unnamed class (§ 10.3.3, p. 392). The classes generated from a lambda contain an overloaded function-call operator. For example, the lambda that we passed as the last argument to stable_sort:

// sort words by size, but maintain alphabetical order for words of the same sizestable_sort(words.begin(), words.end(),            [](const string &a, const string &b)              { return a.size() < b.size();});

acts like an unnamed object ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.