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

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.

主站蜘蛛池模板: 五河县| 海淀区| 罗定市| 昭觉县| 将乐县| 金堂县| 治多县| 镇沅| 武城县| 建德市| 温宿县| 阳信县| 买车| 星座| 江油市| 屏山县| 泰宁县| 南雄市| 金阳县| 思茅市| 乌鲁木齐县| 石狮市| 大荔县| 吴旗县| 时尚| 吉首市| 德兴市| 集安市| 二连浩特市| 镇雄县| 黄陵县| 辉县市| 栾城县| 苍溪县| 寿光市| 东安县| 华阴市| 宣武区| 涟水县| 绥滨县| 云梦县|