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>
typedef std::function<int (int)> F;
F Fix(std::function<F (F)> f)
{
return [=](int t) {return f(Fix(f))(t);};
}
using namespace std;
int main(){
vector<int> v = {1, 2, 3, 4, 5};
// vの要素をそれぞれ階乗して出力
for_each(v.begin(), v.end(), [](int const i){ // 出力用の無名関数
cout <<
Fix([](F f) -> F{ // 「階乗する無名関数」を返す関数。
return [=](int n){
return ((0 == n)?(
1
):(
n * f(n - 1)
));
};
})(i) <<
endl;
});
}
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.