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;}
    });
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM