匿名函数:在计算机编程中是指一类无需定义标识符(函数名)的函数或子程序。
匿名函数具有以下特征:
- 它没有名字(因此是匿名的)
- 内联定义
- 当您不想要正常功能的开销/形式时使用
- 除非作为参数传递给另一个函数,否则不会多次显式引用
1 //all_off example 2 #include <iostream> 3 #include <algorithm> 4 #include <array> 5 using namespace std; 6 7 int main() 8 { 9 std::array<int, 8> foo = { 3, 5, 7, 11, 13, 17, 19, 23 }; 10 if (all_of(foo.begin(), foo.end(), [](int i) {return i % 2; })) 11 { 12 std::cout << "All elements are odd number\n"; 13 } 14 else 15 { 16 std::cout << "All elements are not odd number\n"; 17 } 18 return 0; 19 }
上述的匿名函数可以等价为如下常用形式:
1 bool is_odd(int i) 2 { 3 return i % 2; 4 }