Hi,can you explain the use of **for_each and lambda** in c++11.What are they for,how to use? I have seen a few examples but do not get the meaning.Thank you.
Both of these features are mostly for convienience and cleaner code. What I mean by that is that C++ is still turing complete without either of these features. One major reason for including these into C++ was that people comming from other languages often want to use these features, and they're sometimes not easily breakable into more fundamental parts of the C++ language (in particular lambda).
So called lambda functions (named after Lambda Calculus, a formal system for mathematical logic) are based off of the lambda functions you'd expect to see in functional languages.
The most breif description of a lambda function is a function without a name. Mostly just shorthand. Another interesting property is that it can be passed around like any other variable. Though it should be noted that each lambda is it's own type, thus you need to assign it to auto. You can alternatively use std::function, which is capable of handling any kind of function. Sometimes it can be used as a normal function pointer; I'll explain that latter. One of the more usefull properties of Lambda's are closures. That means that the scope is "saved with the function". So if a variable is accessable from where you defined the lambda, then the value of that variable will be saved when the lambda is created, and will allways be accessable from the lambda (so a variable will not change and will always be accessable). If the lambda does not use closures, then the function is usable as a normal function pointer.
for_each is just a way to "do something with each of the elements of an InputIterator". The "something" it does is the lambda you pass to it.
Edited by Hiroshe