//professional c++ 4th edition p417
#include
#include
#include
#include
#include
std::function<int(void)> multiplyBy2Lambda(int x)
{
return [x]{ return 2 * x; };
}
// Using function return type deduction
//auto multiplyBy2Lambda(int x)
//{
// return [x]{ return 2 * x; };
//}
int main()
{
// Define a generic lambda to find values > 100.
auto isGreaterThan100 = [](auto i){ return i > 100; };
// Use the generic lambda with a vector of integers.
std::vector<int> ints{ 11, 55, 101, 200 };
auto it1 = std::find_if(cbegin(ints), cend(ints), isGreaterThan100);
if (it1 != cend(ints)) {
std::cout << "Found a value > 100: " << *it1 << std::endl;
}
// Use exactly the same generic lambda with a vector of doubles.
std::vector<double> doubles{ 11.1, 55.5, 200.2 };
auto it2 = std::find_if(cbegin(doubles), cend(doubles), isGreaterThan100);
if (it2 != cend(doubles)) {
std::cout << "Found a value > 100: " << *it2 << std::endl;
}
{
double pi = 3.1415;
auto myLambda = [myCapture = "Pi: ", pi]{ std::cout << myCapture << pi; };
myLambda();
}
std::cout << std::endl;
{
auto myPtr = std::make_unique<double>(3.1415);
auto myLambda = [p = std::move(myPtr)]{ std::cout << *p; };
myLambda();
}
std::cout << std::endl;
{
auto myPtr = std::make_unique<double>(3.1415);
auto myLambda = [myPtr = std::move(myPtr)]{ std::cout << *myPtr; };
myLambda();
}
std::cout << std::endl;
//function<int(void)> fn = multiplyBy2Lambda(5);
//std::cout << fn() << std::endl;
auto fn = multiplyBy2Lambda(5);
std::cout << fn() << std::endl;
std::vector<int> vec{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int value = 3; // 从9 开始数 结果是有 6 个数 > 3
int cnt1 = std::count_if(cbegin(vec), cend(vec),
[value](int i){ ret