TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

# Creating Unnamed Functions with the Lambda Library-2 : Page 2

 by Danny Kalev
 Jul 13, 2005
 Page 2 of 4

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

Presenting the Problem
The term a "lambda expression" originates of the mathematical field of lambda calculus. To see what kind of problems a lambda expression can solve, consider the following invocation of the transform() algorithm originally presented in a previous 10-Minute Solution:
``````
string s="hello";
transform(s.begin(), s.end(), s.begin(), toupper);
``````
transform's fourth argument can be any callable entity, say a functor, a bound member function or a freestanding function. Now, suppose you want to apply a different type of transformation to the string—namely mask every character with an asterisk. You want to be able to write something like this:
``````
transform(s.begin(),
s.end(),
s.begin(),
='*');
``````
Of course, this code won't compile. Instead, you have to write a full-blown function first:
```

.qs-listings #asset-middle-b .group {
width: 70% !important;;
}

.qs-listings #bottomline {
width: 70% !important;
}

```
int toasterisk(int original_letter)
{
return '*';
}

And call transform() like this:

transform(s.begin(), s.end(), s.begin(), toasterisk);
``````
Using for_each() instead of transform() for such a task seems more natural:
``````
for_each(s.begin(), s.end(), toasterisk);
``````
But still, the third argument must be the name of a function defined elsewhere in the program. This coding style, though inevitable, is artificial and unwieldy. In some cases, it also compromises encapsulation. Take a look at how to define an unnamed function on the call site using the lambda library.

Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date