作成日
2019/09/02最終更新
2021/12/07記事区分
一般公開C++11 で導入されたラムダ式について簡単なサンプルコードを記載します。
ラムダ式の構文
以下のように記述します。
#include <iostream>
int main() {
auto f = [](std::string mystr){ std::cout << mystr << std::endl;};
f("Hello World");
return 0;
}
[]
後述のキャプチャリストです。()
引数がない場合は省略できます。{}
関数の本体です。
関数の外の変数をキャプチャして使用
値を書き換える場合。
#include <iostream>
int main() {
int x = 1;
// 参照キャプチャ
auto f = [&] { x = 2; };
// auto f = [&x] { x = 2; }; // としてもよい。
f();
std::cout << x << std::endl; //=> 2
return 0;
}
値をコピーして利用するだけの場合。
#include <iostream>
int main() {
int x = 1;
// コピーキャプチャ
auto f = [=] { return x + 1; };
// auto f = [x] { return x + 1; }; // としてもよい。
std::cout << f() << std::endl; //=> 2
std::cout << x << std::endl; //=> 1
return 0;
}
返り値の型を明示
返り値の型を明示的に指定できます。指定しない場合は暗黙的に推論されます。typeid で型を確認できます。
#include <iostream>
#include <typeinfo>
int main() {
auto f = []() { return 1; };
auto g = []()->float { return 1; };
const std::type_info& ti = typeid(f());
std::cout << ti.name() << std::endl; //=> i
const std::type_info& ti2 = typeid(g());
std::cout << ti2.name() << std::endl; //=> f
return 0;
}
ラムダ式を引数および返り値に取る関数
std::function
でラムダ式を引数および返り値に取る関数を定義できます。
#include <iostream>
#include <functional>
std::function< int(int,int) > FF() {
auto f = [](int a, int b) { return a + b; };
return f;
}
void GG(std::function< int(int,int) > FP) {
std::cout << FP(1, 1) << std::endl;
}
int main() {
auto f = FF();
GG(f); //=> 2
return 0;
}
ラムダ式は関数ポインタにキャストすることもできます。
#include <iostream>
typedef int(*FpIII)(int,int);
FpIII FF() {
auto f = [](int a, int b) { return a + b; };
return f;
}
void GG(FpIII FP) {
std::cout << FP(1, 1) << std::endl;
}
int main() {
auto f = FF();
GG(f); //=> 2
return 0;
}
関連記事
- ダウンキャスト (C++をもう一度)実行時型情報 RTTI #include <iostream> #include <typeinfo> using namespace std; class MyClass { public: virtual ~MyClass() {} // typeid で正しい RTTI // (RunTime Type Information; 実行時型情報) ...
- 競技プログラミングの基本処理チートシート (C++)限られた時間の中で問題を解くために必要となる、競技プログラミングにおける基本的な処理のチートシートです。競プロにおけるメジャー言語 C++ を利用します。その際 C++11 の機能は利用せず C++03 の機能の範囲内で記述します。 頻度高く定期的に開催されるコンテスト AtCoder Codeforces main.cpp #include <iostream>
- 構造体と列挙体 (C++をもう一度)構造体 #include <iostream> using namespace std; struct MyStruct { char charval; int intval; }; void Show(MyStruct* obj) { cout << obj->intval << endl; } int main() { ...
- Valgrind による C/C++ メモリリーク検出JVM メモリリークでは JDK の jstat や jmap で原因を調査できます。C/C++ では valgrind の Memcheck ツールが利用できます。valgrind には複数のツールが含まれており既定のツールが Memcheck です。他のツールを利用する場合は --tool オプションで指定します。 [簡単な利用例](h
- クラスの基本/初期化 (C++をもう一度)構造体のように初期化する (非推奨) #include <iostream> using namespace std; const int MAX_STR = 16; class MyClass { public: int m_integer; char m_str[MAX_STR + 1]; void Show(); }; void MyClass::Show...