I was trying to understand how memoization works in C++, so I looked at an example of memoization used in Fib. sequence.
std::map<int, int> fibHash;
int memoized_fib (int n)
{
std::map<int, int>::iterator fibIter = fibHash.find(n);
if( fibIter != fibHash.end() ) return *fibIter;
int fib_val;
if( n <=1 ) fib_val = 1;
else fib_val = memoized_fib ( n-1 ) + memoized_fib ( n-2 );
fibHash[ n ] = fib_val;
return fib_val;
}
I was a little confused with how the fibHash[n] works. Does it just hold the individual values of each fib(#)? Also, the iterator traversess through the index to look for the correct value in the table and returns that? For example fib(6) = find fib(5) and fib(4), already stored and just add them?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…