练习10.14:
编写一个lambda,接受两个int,返回他们的和。
解答:
#include <iostream>
using namespace std;
auto add = [](const int& a, const int& b){
return a + b;};
//等价形式
//auto add = [](const int& a, const int& b) -> int{
// return a + b;};
int main(){
// auto add = [](const int& a, const int& b){
// return a + b;};
cout << add(12, 13) << endl;
}
练习10.15:
编写一个lambda,捕获他所在函数的int,并接受一个int参数。lambda应该返回捕获的int和int参数的和。
解答:
#include <iostream>
using namespace std;
int main(){
int num1 = 10;
auto lambda1 = [&](const int& num2) -> int{
return num1 + num2;};
auto lambda2 = [num1](const int& num2) -> int{
return num1 + num2;};
cout << lambda1(12) << endl;
cout << lambda2(12) << endl;
}
练习10.16:
使用lambda编写你自己版本的biggies。
解答:
我觉得这里重写倒是没有必要,这里可以将书上完整的biggies抄写一份给自己的编译器。
然后,单步调试一遍,看看运行出来都是什么样的结果。
也等于间接的练习了debugger的用法。
练习10.17:
重写10.3.1节练习10.12(第345页)的程序,在对sort的调用中使用lambda来替代函数compareIsbn。
解答:
auto compareIsbn = [](const Sales_data &a, const Sales_data &b){
return a.isbn() > b.isbn();
}
放在适当位置(可以在函数体内。可以尝试放在函数体外,看看编译器是否报错 XD)
练习10.18:
重写biggies,用partition代替find_if。我们在10.3.1节练习10.13(第345页)中介绍了partition算法。
解答:
auto wc = partition(words.begin(), words.end(), [sz](const string &a){return a.size() >= sz; });
单就把find_if改成partition就行了。
可以去查一下,二者在参数组成上几乎一致,行为有所不同。
练习10.19:
用stable_partition重写前一题的程序,与stable_sort类似,在划分后的学列中维持原有元素的顺序。
解答:
auto wc = stable_partition(words.begin(), words.end(), [sz](const string &a){return a.size() >= sz; });
说明一下这里stable的意思
【引用】这种稳定算法位置相等元素原有的顺序。
比如说,原有顺序是{a1 = 1, a2 = 3, a3 = 5, a4 = 9,a5 = 5, a6 = 3}。
在使用stable_sort排序的之后,顺序为 {a1 =1, a2 = 3, a6 = 3, a3 = 5, a5 = 5, a4 =9}
其他的stable算法依次类推。