use*_*129 6 c++ recursion templates memoization c++11
这是我为函数编写的通用memoization包装器.它利用了tuplehash.
template<typename R, typename... Args>
class memofunc{
typedef R (*func)(Args...);
func fun_;
unordered_map<tuple<Args...>, R, tuplehash::hash<tuple<Args...> > > map_;
public:
memofunc(func fu):fun_(fu){}
R operator()(Args&&... args){
auto key = make_tuple(std::forward<Args>(args)...);
auto q = map_.find(key);
if(q == map_.end()){
R res = fun_(std::forward<Args>(args)...);
map_.insert({key,res});
return res;
}else{
return q->second;
}
}
};
Run Code Online (Sandbox Code Playgroud)
Fibonacci数字的使用示例.
long long fibo(long long x){
static memofunc<long long, long long> memf(fibo);
// try to replace fibo with this new fibo but doesn't work, why?
// function<long long(long long)> fibo = memf;
if(x <= 2) return 1;
// this works but involves changing the original code.
// how to write code such that I dont need to manually add this code in?
return memf(x-1) + memf(x-2);
// old code
// return fibo(x-1) + fibo(x-2);
}
Run Code Online (Sandbox Code Playgroud)
问题是,理想情况下,我可以在递归函数的开头添加几行并完成memoization.但简单的替换不起作用,这就是我卡住的地方.
您的问题似乎是您在每次函数调用时制作内存器的本地副本,然后销毁它。
这是一个简单的单参数版本的记忆器,似乎有效:
#include <iostream>
#include <functional>
#include <unordered_map>
template<typename Sig, typename F=Sig* >
struct memoize_t;
template<typename R, typename Arg, typename F>
struct memoize_t<R(Arg), F> {
F f;
mutable std::unordered_map< Arg, R > results;
template<typename... Args>
R operator()( Args&&... args ) const {
Arg a{ std::forward<Args>(args)... }; // in tuple version, std::tuple<...> a
auto it = results.find(a);
if (it != results.end())
return it->second;
R retval = f(a); // in tuple version, use a tuple-to-arg invoker
results.emplace( std::forward<Arg>(a), retval ); // not sure what to do here in tuple version
return retval;
}
};
template<typename F>
memoize_t<F> memoize( F* func ) {
return {func};
}
int foo(int x) {
static auto mem = memoize(foo);
auto&& foo = mem;
std::cout << "processing...\n";
if (x <= 0) return foo(x+2)-foo(x+1); // bwahaha
if (x <= 2) return 1;
return foo(x-1) + foo(x-2);;
}
int main() {
std::cout << foo(10) << "\n";
}
Run Code Online (Sandbox Code Playgroud)
请注意,foo(10)
仅执行 10 次调用foo
。
这也承认:
#define CAT2(A,B,C) A##B##C
#define CAT(A,B,C) CAT2(A,B,C)
#define MEMOIZE(F) \
static auto CAT( memoize_static_, __LINE__, F ) = memoize(F); \
auto&& F = CAT( memoize_static_, __LINE__, F )
int foo(int x) {
MEMOIZE(foo);
std::cout << "processing...\n";
if (x <= 0) return 0;
if (x <= 2) return 1;
return foo(x-1) + foo(x-2);;
}
Run Code Online (Sandbox Code Playgroud)
对于喜欢宏的人来说。
三步版本可能会更好。
首先,前奏是函数和记忆器包装器的前向声明。
其次,在函数内部,为函数名起一个别名,以便递归调用时使用记忆函数。
第三,在函数声明之后,为函数名起一个别名,因此外部调用也使用记忆版本。
上面的代码只记住递归调用,而不是初始调用。
归档时间: |
|
查看次数: |
742 次 |
最近记录: |