lambda函数捕获和返回

1.lambda函数捕获

lambda函数捕获分值捕获和引用捕获

采用值捕获的前提是变量可以拷贝,与参数不同的是被捕获的变量的值是在lambda创建的时候拷贝的,被捕获的变量的值,不会随着改变变量在函数内后面的改变而改变。
void func(){
      size_t v1 = 42;
      auto f = [v1]{ return v1;};
      v1 = 0;
      auto j = f(); //j = 42
}
引用捕获与其他类型的捕获相同。
void func2(){
      size_t v1 = 42;
      auto f = [&v1]{ return v1;};
      v1 = 0;
      auto j = f(); //j = 0
}

2、隐式捕获

除了显式的列出我们我需要函数中那些变量,还可以用 = 或 &,让编译器推断我们使用了那些变量。
其中= 告诉编译器这些变量都是值捕获, 告诉编译器这些变量都是引用捕获。

3、混合捕获

如果我们希望对一部分变量采用值捕获,一部采用引用捕获,那么就可以混合使用隐式捕获和显式捕获。
类似

[&,c] 
[=,&os] //c 和 os都是来自函数的变量

注意在使用混合捕获的时候,第一个元素必须是 & 或 =

4、指定lambda返回类型

当我们需要定义lambda的返回值类型时,必须使用尾置返回类型。

5、书上的例子

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ostream>

void bigged(std::vector<std::string> &words, std::vector<std::string>::size_type sz){
    // sort words by lesss
    std::stable_sort(words.begin(),words.end(),[](const std::string &a, const std::string &b){ return a.size()< b.size();});
    //git the iterator of the  size bigger than sz
    auto wc = std::find_if(words.begin(),words.end(),[sz](const std::string &a){ return a.size()>sz;});
    //get the number of total number minus the number which begin wc and end in words.end
    auto count = words.end() - wc;
    std::cout<<count<<" "<<make_plural(count, "word", "s")<<"of length "<< sz  <<" or langer " <<std::endl;
    // print result
    for_each(wc,words.end(),[](const std::string &s){ std::cout<<s<<" ";});  
}

std::string make_plural(size_t count, const std::string &word, const std::string &ending){
    return (count > 1) ? word +ending : ending;
}

void biggies(std::vector<std::string> &words, std::vector<std::string>::size_type sz, std::ostream &os = std::cout,char c = ' '){
    std::for_each(words.begin(),words.end(),[&os, c](const std::string &s){ os << s << c;});
}

void AbsVector(std::vector<int> *vec_ptr){

    std::transform(vec_ptr->begin(),vec_ptr->end(),vec_ptr->begin(),[](int i) -> int{
        if(i>0){ return i;}else{ return -i;}
    });
}
posted @ 2020-08-13 16:00  cyssmile  阅读(1490)  评论(0编辑  收藏  举报