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
Well the neatest way I can think of to do this in C++ is probably using a function object to store the memoized values. I guess this is probably slightly similar to your python decorator, although I have never really done any python. The code would look something like this:
template
class mem {
std::map mem_map;
public:
T operator()(T input) {
typename std::map::iterator it;
it = mem_map.find(input);
if (it != mem_map.end()) {
return it->second;
} else {
T output = calc(input);
mem_map[input] = output;
return output;
}
}
};
The code defines a template class that takes in a typename and a function pointer, the function operator is then defined on the class allowing it to be called. The function operator takes in an input value checks if said value is in a map, then either simply returns it from the map or calculates it (using the function pointer), adds it to the map and then returns it.
So assuming you define some processing function like say:
int unity(int in) { return in; }
You would use the code like this:
mem mem_unity;
int y;
y = mem_unity(10);
So we define an instance of the mem class which takes our value type and processing function as template parameters, then simply call this class as a function.