Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
  1. What is the necessity to use lambda functions and expressions in C++?

  2. Can you explain or show through examples how to use lambda functions and expressions?

  3. I already gone through the related Wikipedia page, but I got only few ideas regarding this. Are there more resources I can read?

May I know which compilers will fully support this lambda feature? Some answers I found are VS10 and GCC5 compilers. Is there any online compilers which are supporting this feature?


migration rejected from Nov 23 '15 at 16:30

This question came from our site for professional and enthusiast programmers. Votes, comments, and answers are locked due to the question being closed here, but it may be eligible for editing and reopening on the site where it originated.

closed as too broad by gbjbaanb, Scant Roger, GlenH7 Nov 23 '15 at 16:30

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

in a word: <algorithms> – jk. Feb 5 '13 at 10:17
There is never a necessity to use anything. All there is are cases where the new features make code significantly simpler. – Jan Hudec Feb 5 '13 at 11:45

There are other use cases of lambdas, and that's local functions. For example, look at the Windows file iteration API.

You have to call once, process one result, and then you can write a loop to iterate over the rest, forcing duplication in the code.

The most encapsulated and DRY-adhering way to write this is to use a lambda function. It's encapsulated to the current scope, can access local variables easily so you can do whatever logic you want easily. You call it once with the first result, and then again in the loop with the other results.

There are other similar times when writing logic that is effectively inline but still re-usable is very helpful- it keeps high encapsulation but still allows DRY.


Well one practical use I found out is reducing boiler plate code. For example,

auto print_board = [](const vector<int>& board, int bsize) {
        for(int i = 0; i<bsize; i++){
        for(int j=0; j<bsize; j++){
            cout << board[bsize*i+j] << " ";
        cout << "\n";

Without lambda, you may need to do sth for different bsize cases. Of course you could create a function but what if you want to limit the usage of this lambda with in a scope of a function rather than creating defining a function outside the scope of the function? So I like it for this case.