0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++ラムダ式解説

Last updated at Posted at 2018-12-18

#1.copyとreference
copyとreferenceでは出力の値が異なります。

copyの場合

#include<iostream>

int main(){
   auto v = 1;
   auto copy = [v]() mutable {
      std::cout<<v<<std::endl;
      ++v;
    };
   copy();
   copy();
   std::cout<<v;
}

v:1 2 1

referenceの場合

#include<iostream>

int main(){
   auto v = 1;
   auto ref = [&]() {
      std::cout<<v<<std::endl;
      ++v;
    };
   ref();
   ref();
   std::cout<<v;
}

v:1 2 3

#2.functionとラムダを組み合わせて

#include<iostream>
#include<functional>
int main(){
   auto func = std::function<void(int)>{};
   func = [](int q){std::cout<<q;};
   func(777);
   
   auto one = 1;
   func = [one](int v){ std::cout << (v + one);};
   func(1);
}

777
2

function objectを作り、ラムダでキャプチャー。

#lambdaとfunction
lambda関数はコンパイル時、inline関数が生成されます。
一方、functionの場合、inline関数は生成されませんが、inlineの様な役割となります。

しかし、ラムダ関数でfunctionを適用した場合、ヒープ領域となるので、パフォーマンスが悪化します。

#結論
std::functionを頼らず、lambda関数を構築しようね!
僕はラムダの神になりたいと常々思ってます。
続編を待たれよ。

0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?