Home > Article > Backend Development > What are the usage scenarios of lambda expressions in C++ functions?
Lambda expressions are anonymous functions that can be used to simplify code, as callback functions, or parameterized functions. The advantages include simplified code, reduced redundancy, and increased flexibility.
Usage scenarios of lambda expressions in C functions
lambda expression is an anonymous function that can be defined within the function body and use. Unlike ordinary functions, lambda expressions have no name and can only be used within the scope in which it is defined.
Usage scenarios:
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; // 使用 lambda 表达式增加每个元素 std::for_each(numbers.begin(), numbers.end(), [](int& n) { n++; }); // 打印增加后的列表 for (int num : numbers) { std::cout << num << " "; } return 0; }
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 5, 2, 4, 3}; // 使用 lambda 表达式对列表排序 std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a < b; }); // 打印排序后的列表 for (int num : numbers) { std::cout << num << " "; } return 0; }
#include <iostream> #include <vector> void for_each(std::vector<int>& numbers, std::function<void(int&)> operation) { for (int& num : numbers) { operation(num); } } int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; // 使用 lambda 表达式参数化 for_each 函数 for_each(numbers, [](int& n) { n *= n; }); // 打印平方后的列表 for (int num : numbers) { std::cout << num << " "; } return 0; }
Advantages:
The above is the detailed content of What are the usage scenarios of lambda expressions in C++ functions?. For more information, please follow other related articles on the PHP Chinese website!