Lambda functions in C++

The lambda functions are nested functions used to implement inline logic instead of implementing function objects or functors. The states of the variable is also maintained which ensures no loss of data. These anonymous functions make the code less error prone.

Lets us take an example of std::for_each, where we want to sum the entities of a vector of integers. In a conventional way, we can do it using function object and function pointers in below manner:

[gist /]

We have to define a function and have to use the function pointer in std::for_each to implement the sum logic. Also when the function object has to be used, we have to define a struct and have to override the operator() function to customize the implementation for sum.

This can be overcome by using lambda expressions. Let us now rewrite the same logic using lambda captures

[gist /]

The above implementation is not only readable but the lambda make the code inline so not other implementation has to be written.

Tagged with: , , , , , ,
Posted in CPP

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 353 other followers

%d bloggers like this: