- 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.
推薦閱讀
- Learn Blockchain Programming with JavaScript
- 國際大學生程序設計競賽中山大學內部選拔真題解(二)
- 程序員面試筆試寶典
- 趣學Python算法100例
- C語言從入門到精通(第4版)
- Python Network Programming Cookbook(Second Edition)
- 零基礎輕松學SQL Server 2016
- 用戶體驗可視化指南
- .NET 4.5 Parallel Extensions Cookbook
- Deep Learning with R Cookbook
- Android應用開發實戰
- 邊玩邊學Scratch3.0少兒趣味編程
- C語言程序設計教程
- 軟件測試(慕課版)
- Clojure Data Structures and Algorithms Cookbook