While reading a sample code I came across this

what is the meaning of this when [] brackets are written before ?
I mean what is the meaning of [](int i) on the line 9.
1
2
3
4
5
6
7
8
9
10
11
12
13
  // all_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::all_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {3,5,7,11,13,17,19,23};

  if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
    std::cout << "All the elements are odd numbers.\n";

  return 0;
}
[](int i) is the capture list and argument list for that lambda function.

[] is an empty capture list, so nothing is captured.

(int i) is saying this lambda function takes an int (by value) as an argument.
It is a lambda expression, introduced in C++11:
http://en.cppreference.com/w/cpp/language/lambda

Furthermore, it is not just the [](int i), it is the whole [](int i){return i%2;}

Remember that std::all_of takes three arguments: (InputIterator, InputIterator, UnaryPredicate)
http://www.cplusplus.com/reference/algorithm/all_of/

In your code the foo.begin() and foo.end() are clearly iterators and between the last comma and closing parentheses there is [](int i){return i%2;}


Before C++11 you had to use a named functor (function or function object) in generic algorithms:
1
2
3
4
5
6
7
8
9
10
bool IsOdd( int i ) { return i%2; }

int main () {
  std::array<int,8> foo = {3,5,7,11,13,17,19,23};

  if ( std::all_of(foo.begin(), foo.end(), IsOdd) )
    std::cout << "All the elements are odd numbers.\n";

  return 0;
}

Consider that your function (here the main) is long. When the reader encounters the IsOdd, they have to jump upwards (or to headers) to find out what the IsOdd does. Such tiny function is more convenient in-place, but one cannot define named functions inside functions.


The [] can hold captures. The lambda can access variables of the calling function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>     // std::cout
#include <algorithm>    // std::all_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {3,5,7,11,14,17,19,23};
  int count {};

  if ( std::all_of(foo.begin(), foo.end(),
       [&count](int i){++count; return i%2;}) )
    std::cout << "All the elements are odd numbers.\n";

  std::cout << "Tested elements: " << count << '\n';
  return 0;
}
Topic archived. No new replies allowed.