c++ primer第五版(中文)习题答案 第十章第三节第三小节-lambda捕获和返回

来源:互联网 发布:网络黄金 编辑:程序博客网 时间:2024/05/01 07:59

本博客知识记录自己学习中的笔记或者记录,如果有错误欢迎大家纠正。

本节继续学习c++11的新特性lambda表达式

10.20标准库定义了一个名为count_if的算法,类似find_if,此函数接收一对迭代器,表示输入范围,还接受一个谓词,会对输入范围中的每个元素执行。count_if返回一个计数值,表示谓词有多少次为真,使用count_if重写我们重写统计有多少单词超过6的部分。

#include <iostream>#include <vector>#include <string>#include <algorithm>//将words按字典排序,删除重复单词void elimDups(std::vector<std::string> &words){    //排序    sort(words.begin(), words.end());    auto end_unique = unique(words.begin(), words.end());    words.erase(end_unique, words.end());}//make_plural(wc, "word ", "s ")当输入中文本中word数大于一是在word后加s,为words为word的复数!std::string make_plural(size_t ctr, const std::string &word, const std::string &ending){    return (ctr == 1) ? word : word + ending;}//原版void biggies(std::vector<std::string> &words,    std::vector<std::string>::size_type sz){    elimDups(words);//将words按字典排序,删除重复单词    //按长度排序,长度相同的单词维持字典排序    //  stable_sort(words.begin(), words.end(),    //      [](const std::string &a, const std::string &b)    //  {return a.size() >= b.size(); });    stable_partition(words.begin(), words.end(),        [sz](const std::string &a)    {return a.size() <= sz;  });    //获取一个迭代器,指向第一个满足size()>=sz的元素    auto count = count_if(words.begin(), words.end(),        [sz](const std::string &a)    {return a.size() > sz; });    //计算满足size>=sz的元素的数目    //auto count = words.end() - wc;    std::cout << count << " " << make_plural(count, "word", "s")        << " of length " << sz << " or longer " << std::endl;    std::cout << std::endl;}int main(){    std::vector<std::string>vecString;    std::string s = "";    //注意在win下使用ctrl+z结束输入     while (std::cin >> s)    {        vecString.push_back(s);    }    biggies(vecString, 6);    system("pause");    return 0;}

输出结果为:
这里写图片描述

10.21编写一个lambda,捕获一个局部int变量,并递减变量值,直到它为0.一旦变量为0,在调用lambda应该不在递减变量。lambda应该返回一个bool值,指出捕获的变量是否为0;

#include <iostream>#include <string>int main(){    int count;    std::string boolStr = "";    std::cout << "input a number:" << std::endl;    std::cin >> count ;    //定义一个函数指针 接收lambda表达式    auto f = [&count]()->bool    {        bool b = false;        if (count==0)            b = true;        while (count>0)            count--;        return b;    };    if (f())        boolStr = "true";    else        boolStr = "false";    std::cout << "the number  is Zero :is " << boolStr << std::endl;    system("pause");    return 0;}

输入不为0时 的结果为
这里写图片描述
输入0时的结果为
这里写图片描述

lambda捕获列表
[] 空捕获列表。lambda不能使用说在函数中的变量,一个lambda只有捕获变量后才能使用它们。

[names] names是一个逗号分隔的名字列表[name1,name2]这些名字都是lambda表达式所在函数的局部变量。默认情况下,捕获列表的变量都被拷贝,名字前面使用了&,则采用引用捕获方式

[&] 隐式捕获列表,采用引用捕获方式,lambda体中所使用的所在函数的实体都采用引用方式使用

[=] 隐式捕获列表,采用值捕获方式,lambda体中所使用的所在函数的实体都采用值方式使用

[& ,names] names是一个逗号分隔的名字列表[&,name1,name2]names这些变量采用值捕获方式,而其他采用引用方式

[= ,names] names是一个逗号分隔的名字列表[=,&name1,&name2]names这些变量采用引用捕获方式,而其他采用值方式
其中names不能包含this,并且都要在前面加上&符号

0 0