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

Using the Lambda expression for a tiny function

Imagine we have a tiny one-line function that we invoke only once. It's better if we write the operation of that function directly when we need it. We actually had this function in our previous example when discussing the C++ Standard Library. Just go back to the for_each.cpp file and we will find the PrintOut() function that is only invoked once by for_each(). We can make this for_each loop more readable if we use Lambda. Let's take a look at the following code snippet to examine how we refactor the for_each.cpp file:

    /* lambda_tiny_func.cpp */
#include <vector>
#include <algorithm>
#include <iostream>
#include "../vehicle/vehicle.h"

using namespace std;

auto main() -> int
{
cout << "[lambda_tiny_func.cpp]" << endl;

// Initializing several Vehicle instances
Vehicle car("car", 4);
Vehicle motorcycle("motorcycle", 2);
Vehicle bicycle("bicycle", 2);
Vehicle bus("bus", 6);

// Assigning the preceding Vehicle instances to a vector
vector<Vehicle> vehicles = { car, motorcycle, bicycle, bus };

// Displaying the elements of the vector
// using Lambda expression
cout << "All vehicles:" << endl;
for_each(
begin(vehicles),
end(vehicles),
[](const Vehicle &vehicle){
cout << vehicle.GetType() << endl;
});

return 0;
}

As we can see, we have transformed the PrintOut() function that we used in the for_each.cpp file into a Lambda expression and passed it to the for_each loop. It will indeed give the same output as the for_each.cpp file does. However, now our code becomes more concise and readable.

主站蜘蛛池模板: 河池市| 康马县| 会东县| 通化市| 包头市| 呼伦贝尔市| 湖北省| 钟山县| 兴义市| 郑州市| 安溪县| 云和县| 建阳市| 大连市| 祁门县| 宁安市| 太湖县| 伊通| 安康市| 洱源县| 仪陇县| 宁城县| 济南市| 子洲县| 乌拉特前旗| 琼结县| 潜山县| 新宾| 松阳县| 乡城县| 泸溪县| 宜州市| 乐都县| 吉林省| 固镇县| 昌邑市| 甘孜县| 黎城县| 宝应县| 永泰县| 康保县|