fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <unordered_map>
  4.  
  5.  
  6. template<typename Sig, typename F=Sig* >
  7. struct memoize_t;
  8. template<typename R, typename Arg, typename F>
  9. struct memoize_t<R(Arg), F> {
  10. F f;
  11. mutable std::unordered_map< Arg, R > results;
  12. R operator()( Arg a ) const {
  13. auto it = results.find(a);
  14. if (it != results.end())
  15. return it->second;
  16. else
  17. return results[a] = f(a);
  18. }
  19. };
  20.  
  21. template<typename F>
  22. memoize_t<F> memoize( F* func ) {
  23. return {func};
  24. }
  25.  
  26. int foo(int x) {
  27. static auto mem = memoize(foo);
  28. auto&& foo = mem;
  29. std::cout << "processing...\n";
  30. if (x <= 0) return 0;
  31. if (x <= 2) return 1;
  32. return foo(x-1) + foo(x-2);;
  33. }
  34. int main() {
  35. std::cout << foo(10) << "\n";
  36. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
processing...
processing...
processing...
processing...
processing...
processing...
processing...
processing...
processing...
processing...
55