Last active
June 7, 2022 12:21
-
-
Save hjroh0315/65f00a0b51cfa8c214efe58371f44782 to your computer and use it in GitHub Desktop.
@cache in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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