2

In the following example code of the STL algorithm std::all_of,

What does '[](int i){ return i % 2 == 0; }' mean?

int main() { 

    std::vector<int> v{10, 2, 4, 6}; 

    if (std::all_of(v.begin(), v.end(), [](int i){ return i % 2 == 0; })) { 
        std::cout << "All numbers are even\n"; 
    } 
    else{
        std::cout << "All numbers are not even\n"; 
    }
}
Christopher Oezbek
  • 17,629
  • 3
  • 48
  • 71
Lorenzo
  • 49
  • 3

1 Answers1

1

It's a lambda function that checks if i is even or not. It will return true if i is even, otherwise false.

It's logic is equivalent to this:

#include <algorithm>
#include <iostream>

bool isEven(int i) {
  return i % 2 == 0;
}

int main() { 

    std::vector<int> v{10, 2, 4, 6}; 

    if (std::all_of(v.begin(), v.end(), isEven)) { 
        std::cout << "All numbers are even\n"; 
    } 
    else{
        std::cout << "All numbers are not even\n"; 
    }
}

Output:

All numbers are even


Note: This is lambda method is a free function, and it does not capture anything.

PS: That lambda method has nothing to do with STL.

gsamaras
  • 66,800
  • 33
  • 152
  • 256
  • 2
    Looks like I still need to study these lambda functions, thank you – Lorenzo Aug 04 '19 at 16:40
  • @Lorenzo the λ methods can come in handy, think about it abstractly as an anonymous method, check them out and have fun... Welcome to Stack Overflow by the way! :) – gsamaras Aug 04 '19 at 17:11