- Learning C++ Functional Programming
- Wisnu Anggoro
- 247字
- 2021-07-02 20:51:37
Using the Lambda expression for multiline functions
The Lambda expression can also be used for multiline functions, so we can put the body of the function on it. This will make our code more readable as well. Let's make a new code. In that code, we will have an integer collection and an intent to inspect whether the selected element is the prime number or not. We can make a separate function, for instance, PrintPrime(), then invoke it. However, since the prime number checking operation is called only once, it's more readable if we transform it into a Lambda expression. The code should look like this:
/* lambda_multiline_func.cpp */
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
auto main() -> int
{
cout << "[lambda_multiline_func.cpp]" << endl;
// Initializing a vector containing integer element
vector<int> vect;
for (int i = 0; i < 10; ++i)
vect.push_back(i);
// Displaying whether or not the element is prime number
for_each(
begin(vect),
end(vect),
[](int n) {
cout << n << " is";
if(n < 2)
{
if(n == 0)
cout << " not";
}
else
{
for (int j = 2; j < n; ++j)
{
if (n % j == 0)
{
cout << " not";
break;
}
}
}
cout << " prime number" << endl;
});
return 0;
}
The output we should see on the screen is as follows:

As we can see in the preceding screenshot, we have successfully identified the prime number by using the Lambda expression.
推薦閱讀
- JBoss Weld CDI for Java Platform
- 大學計算機基礎實驗教程
- Visual FoxPro程序設計教程
- C++ Builder 6.0下OpenGL編程技術
- 信息可視化的藝術:信息可視化在英國
- 軟件測試工程師面試秘籍
- Swift 3 New Features
- 用戶體驗增長:數字化·智能化·綠色化
- R Data Analysis Cookbook(Second Edition)
- PySide 6/PyQt 6快速開發與實戰
- Python爬蟲、數據分析與可視化:工具詳解與案例實戰
- Mastering ASP.NET Core 2.0
- 零基礎PHP從入門到精通
- The Applied Data Science Workshop
- Python程序設計:基礎與實踐