Last active
December 15, 2015 13:59
-
-
Save artsobolev/5270779 to your computer and use it in GitHub Desktop.
C++11 function memoizator [http://barmaley-exe.koding.com/en/memoization-using-cpp11]
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 "Memoizator.hpp" | |
int f(int a) { | |
std::cout << __func__ << "(" << a << ")\n"; | |
return a*a; | |
} | |
int g(int a, int b) { | |
std::cout << __func__ << "(" << a << ", " << b << ")\n"; | |
return a*b; | |
} | |
int main() { | |
auto memo_f = memoize(f); | |
auto memo_g = memoize(g); | |
int v; | |
for (int i = 0; i < 100; ++i) { | |
v += memo_f(i % 17) * memo_g(i % 91, i % 37); | |
} | |
std::cout << v << std::endl; | |
return 0; | |
} |
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
#ifndef MEMOIZATOR | |
#define MEMOIZATOR | |
#include <tuple> | |
#include <map> | |
template<class R, class... Args> | |
class Memoizator { | |
typedef std::tuple<Args...> tuple; | |
public: | |
typedef R (*function)(Args...); | |
Memoizator(function f) : f(f) {} | |
R operator()(Args... args) { | |
tuple argset(args...); | |
auto it = map.find(argset); | |
if (it != map.end()) { | |
return it->second; | |
} | |
return map[argset] = f(args...); | |
} | |
private: | |
function f; | |
std::map<tuple, R> map; | |
}; | |
template<class R, class... Args> | |
Memoizator<R, Args...> memoize(R (*f)(Args...)) { | |
return Memoizator<R, Args...>(f); | |
} | |
#endif // MEMOIZATOR |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment