Home > Article > Backend Development > How are C++ Lambda expressions used in functional programming?
C++ Lambda expression is a convenient functional programming tool. The syntax is: [capture_list] (parameter_list) -> return_type { body }Practical example: Sorting: Sorting the word list by string length Filter: Filtering can be 3 List of numbers that are divisible
In C++, lambda expression is the most convenient way to pass Code blocks are returned as function arguments or values. Their concise syntax and powerful functionality make them powerful tools for functional programming.
lambda expressions have the following syntax format:
[capture_list] (parameter_list) -> return_type { body }
1. Sorting Case
Use lambda expression to sort the word list by string length:
#include <vector> #include <algorithm> int main() { std::vector<std::string> words = {"Hello", "World", "Lambda", "Expression"}; std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { return a.size() < b.size(); }); for (const auto& word : words) { std::cout << word << "\n"; } return 0; }
Output:
Hello Lambda World Expression
2. Filter case
Filter out the list of numbers that are divisible by 3:
#include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> filteredNumbers; std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(filteredNumbers), [](int number) { return number % 3 == 0; }); for (const auto& number : filteredNumbers) { std::cout << number << "\n"; } return 0; }
Output:
3 6 9
The above is the detailed content of How are C++ Lambda expressions used in functional programming?. For more information, please follow other related articles on the PHP Chinese website!