Memoized, recursive factorial function?

前端 未结 4 1032
庸人自扰
庸人自扰 2020-12-03 04:21

I know how to do memoization in Python easily but I need a faster way to compute them, so I am using C++. However, I have no clue how to memoize. I understand that it\'s abo

4条回答
  •  一向
    一向 (楼主)
    2020-12-03 04:49

    I like relying on lambda capture as in (uses std=c++14)

    template
    auto memoize(std::function&& f)
    {
      using F = std::function;
      std::map,R> cache;
      return ([cache = std::map,R>{}, 
               f = std::forward(f)](Args&&... args) mutable
        {
          std::tuple t(args...);
          if (cache.find(t) == cache.end())
            {
              R r = f(std::forward(args)...);
              cache[t] = r;
            }
          return cache[t];
        });
    }
    

提交回复
热议问题