Skip to content

Instantly share code, notes, and snippets.

@hjroh0315
Last active June 7, 2022 12:21
Show Gist options
  • Select an option

  • Save hjroh0315/65f00a0b51cfa8c214efe58371f44782 to your computer and use it in GitHub Desktop.

Select an option

Save hjroh0315/65f00a0b51cfa8c214efe58371f44782 to your computer and use it in GitHub Desktop.
@cache in C++
#include<iostream>
#include<functional>
#include<map>
#include<tuple>
using namespace std;
// start class definition
template<class>
struct memoize{};
template<class R, class... Args>
struct memoize<R(Args...)>
{
map<tuple<Args...>,R> db;
function<R(Args...)> func;
template<class T>
memoize(T t):func(t){}
R operator()(Args... Ar)
{
if(db.count({Ar...}))
return db[{Ar...}];
R res=func(Ar...);
db[{Ar...}]=res;return res;
}
};
// end class definition
memoize<long(int,int)> binom=
[](int n,int r)->long
{
if(r==0||r==n)return 1;
if(r==1||r==n-1)return n;
return (binom(n-1,r-1)+binom(n-1,r));
};
// usage example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment