2018.10.19——10.3定制操作

本文深入探讨了C++中Lambda表达式的应用,包括匿名函数的定义与调用,以及如何利用Lambda表达式优化STL算法,如sort和find_if。通过实例展示了如何使用Lambda表达式进行字符串排序和查找,以及如何处理vector容器中的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

10.14

[] (const int &a, const int &b) {return a+b;}

答案

#include <iostream>

using namespace std;

int main(int argc, char *[])
{
	auto sum = [] (int a, int b) { return a+b;};
	cout << sum(1, 1) << endl;
	return 0;
}

10.15

include <iostream>

using namespace std;

int fuc(int a)
{
	auto sum = [a] (int b) {return a+b;};		//没有给b赋值
	return sum;
}

int main()
{
	cout << fuc(1) << endl;
	return 0;
}

答案

#include <iostream>
using namespace std;
void add(int a)
{
	auto sum = [a] (int b) {return a + b;};
	cout << sum(1) << endl;
}
int main()
{
	add(1);
	add(2);
	return 0;
}

10.16

void bigies(vector<string> words, vector<string>::size_type sz)
{
	elimdups(words);		//将words里的单词按字典序排列,删除重复单词
	// 按长度排序,长度相同的单词维持字典序
	stable_sort(words.begin(), words.end(), [] (const string &a, const string &b) {return a.size < b.size();});
	//获取一个迭代器,指向满足size() >= sz的元素
	auto wc = find_if(words.begin(), words.end(), [sz] (const string &a) {return a.size > sz;});
	//计算满足size >= sz的元素的数目
	auto count = words.end() - wc;
	cout << count <<" "<< make_plural(count, "word", "s") << " of length " << sz << " or lenger " << endl;
	//打印长度大于等于给定值的单词,每个单词后接一个空格
	for_each(wc. words.end(), [] (const string &s) { cout << s << " ";});
	cout << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值