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

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.

主站蜘蛛池模板: 郁南县| 兴义市| 罗甸县| 灵丘县| 温州市| 嘉黎县| 松溪县| 化隆| 大渡口区| 曲阜市| 辉南县| 东兰县| 哈巴河县| 阳谷县| 抚宁县| 如东县| 武鸣县| 阳东县| 安塞县| 桂平市| 西安市| 波密县| 兴安县| 德州市| 中山市| 黑水县| 乃东县| 宜君县| 年辖:市辖区| 临江市| 湘西| 静乐县| 湾仔区| 镇原县| 宿松县| 江源县| 沙坪坝区| 商水县| 河北区| 万盛区| 北宁市|