C++ Lambda Expressions: Powerful Tools for Specific Scenarios
Introduction
Lambda An expression is an anonymous function introduced in C++ that allows you to create short, inline function objects. They're great for handling simple tasks that don't require declarations or separate naming.
Lambda syntax
Lambda expressions adopt the following syntax:
[capture-list](parameters) -> return-type { body }
Uses
Lambda expressions are particularly useful in the following scenarios:
std::sort
and std::find
. Practical case
1. As a callback function
The following code uses lambda expressions to convert strings For uppercase:
#include <iostream> #include <string> using namespace std; int main() { string str = "hello"; transform(str.begin(), str.end(), str.begin(), [](char c) { return toupper(c); }); cout << str << endl; // 输出:HELLO return 0; }
2. As STL algorithm parameter
The following code uses lambda expression to find the first number greater than 5:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> nums = {1, 3, 5, 7, 9}; auto it = find_if(nums.begin(), nums.end(), [](int n) { return n > 5; }); if (it != nums.end()) { cout << "找到了第一个大于 5 的数字:" << *it << endl; // 输出:7 } else { cout << "没有找到大于 5 的数字" << endl; } return 0; }
3. As a closure
The following code demonstrates how to create a closure using a lambda expression:
#include <iostream> using namespace std; int main() { int x = 10; auto f = [x](int y) { return x + y; }; cout << f(5) << endl; // 输出:15 return 0; }
Note: Compare to named functions , Lambda expressions have the following limitations:
When using lambda expressions, carefully weigh their advantages and limitations to determine whether they are the best choice for a specific scenario.
The above is the detailed content of In what scenarios are C++ lambda expressions particularly useful?. For more information, please follow other related articles on the PHP Chinese website!