I'm trying to use Dynamic Programming to implement fibonacci. Here's my .h file:
#ifndef DYNAMICPROGRAMMING_H
#define DYNAMICPROGRAMMING_H
#include <map>
class DynamicProgramming
{
public:
DynamicProgramming ();
~DynamicProgramming ();
int Fibonacci(int value);
private:
};
#endif // DYNAMICPROGRAMMING_H
Here's the relevant part in my .cpp file:
int DynamicProgramming::Fibonacci(int value)
{
int result;
std::map<int,int>fibonacci_storage;
std::map<int,int>::iterator valueFinder;
if (value == valueFinder->second){
return fibonacci_storage[value];
}
if (value <= 2 ){
result = 1;
} else {
result = Fibonacci(value - 1) + Fibonacci(value - 2);
}
fibonacci_storage.insert(std::pair<int,int>(value,result));
return result;
}
My error is coming from this line: if (value == valueFinder->second)
. This is what it says:
could not convert '((DynamicProgramming*)this)->DynamicProgramming::fibonacci_storage.std::map<_Key, _Tp, _Compare, _Alloc>::find [with _Key = int, _Tp = int, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, int> >, std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const int, int> >, std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]((*(const key_type*)(& value)))' from 'std::map<int, int>::iterator {aka std::_Rb_tree_iterator<std::pair<const int, int> >}' to 'bool'
It looks to me like this is a very simple error, but I'm not sure what all that stuff means. Can someone help me out, I'd really like to master this language, it seems like it would be very useful.
valueFinder
is just an iterator for the type std::map<int,int>
that is not associated to any instance of that type.
To associate it to an instance (here fibonacci_storage) you have to assign it to that instance, i.e.
valueFinder = fibonacci_storage.begin();
Finding an element can be done with source
valueFinder = fibonacci_storage.find(value);
where value is the key you are searching for. Now you check if value is in the map:
if( valueFinder != fibonacci_storage.end() )
{
// value found
}
and you're done.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다