Skip to content

Instantly share code, notes, and snippets.

@pseuxdonimo
Created March 7, 2012 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pseuxdonimo/1992944 to your computer and use it in GitHub Desktop.
Save pseuxdonimo/1992944 to your computer and use it in GitHub Desktop.
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