I recently read about memoization for the first time(I'm a noob) and I wanted to try and make a fibonacci function that uses memoization. This is what I've tried, but anything over 1 just gives me a segmentation fault. Any help is appreciated!
unsigned int fibonacci( unsigned int n )
{
vector<unsigned int> fibvector;
if ( n <= 1 )
return n;
if ( fibvector.size() >= n )
return fibvector[n];
unsigned int add = fibonacci( n-1 ) + fibonacci( n-2 );
fibvector[n] = add;
return add;
}
[n]to access its contents.push_back(n). When you use[n], it returns a reference to a memory address that it hasn't allocated space for internally. Only after you usepush_backcan you do that.