- Learning C++ Functional Programming
- Wisnu Anggoro
- 237字
- 2021-07-02 20:51:37
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.
- Wireshark Network Security
- Troubleshooting PostgreSQL
- Expert Data Visualization
- Building Android UIs with Custom Views
- C和C++游戲趣味編程
- Mastering C++ Multithreading
- UNIX Linux程序設(shè)計教程
- UML2面向?qū)ο蠓治雠c設(shè)計(第2版)
- Learning Splunk Web Framework
- Java EE Web應(yīng)用開發(fā)基礎(chǔ)
- 零基礎(chǔ)學(xué)C++(升級版)
- Continuous Delivery and DevOps:A Quickstart Guide Second Edition
- 一覽眾山?。篈SP.NET Web開發(fā)修行實錄
- ASP.NET本質(zhì)論
- Neo4j Graph Data Modeling