Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C++11のラムダ式で再帰
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main(){
using namespace std;
vector<int> v = {1, 2, 3, 4, 5};
// vの要素をそれぞれ階乗して出力
function<int (int)> f; // 再帰用に宣言
for_each(v.begin(), v.end(), [&f](int const i){ // 出力用の無名関数
cout <<
( // std::function<int (int)> // 本当はここが良い
f = [&f](int n){ // 階乗する無名関数。再帰のためにfを参照している
return ((0 == n)?(
1
):(
n * f(n - 1)
));
})(i) <<
endl;
});
}
/* <-
1
2
6
24
120
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.