- 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.
推薦閱讀
- C# 7 and .NET Core Cookbook
- TypeScript Essentials
- Oracle Exadata性能優(yōu)化
- Bulma必知必會(huì)
- 人人都是網(wǎng)站分析師:從分析師的視角理解網(wǎng)站和解讀數(shù)據(jù)
- MySQL數(shù)據(jù)庫(kù)管理與開(kāi)發(fā)(慕課版)
- PhoneGap:Beginner's Guide(Third Edition)
- Windows Embedded CE 6.0程序設(shè)計(jì)實(shí)戰(zhàn)
- Vue.js應(yīng)用測(cè)試
- Java7程序設(shè)計(jì)入門(mén)經(jīng)典
- Head First Kotlin程序設(shè)計(jì)
- Java核心編程
- Visual C++程序設(shè)計(jì)全程指南
- 可視化H5頁(yè)面設(shè)計(jì)與制作:Mugeda標(biāo)準(zhǔn)教程
- C語(yǔ)言程序設(shè)計(jì)