官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 淳安县| 济源市| 双峰县| 永和县| 都安| 容城县| 公主岭市| 余干县| 柳林县| 芮城县| 酒泉市| 贵德县| 旌德县| 会东县| 汉阴县| 达孜县| 静宁县| 安康市| 金沙县| 平和县| 璧山县| 六安市| 禄丰县| 尚义县| 类乌齐县| 文登市| 镇宁| 武宁县| 偏关县| 都昌县| 大悟县| 临潭县| 集安市| 新竹市| 梁山县| 隆回县| 攀枝花市| 崇信县| 商丘市| 秦安县| 安国市|