板凳——————————————————c++(65)

本文通过实例详细介绍了C++17中`std::accumulate`函数的用法,包括透明操作符、通用谓词及不同类型的累加计算。文中展示了如何使用lambda表达式、自定义函数、成员函数对象进行累加,并讨论了几何平均数的计算。同时,还探讨了`std::logical_and<>`和`std::logical_or<>`在累加中的应用。
摘要由CSDN通过智能技术生成

//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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值