fibonacci.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* Boost.Flyweight example of flyweight-based memoization.
  2. *
  3. * Copyright 2006-2008 Joaquin M Lopez Munoz.
  4. * Distributed under the Boost Software License, Version 1.0.
  5. * (See accompanying file LICENSE_1_0.txt or copy at
  6. * http://www.boost.org/LICENSE_1_0.txt)
  7. *
  8. * See http://www.boost.org/libs/flyweight for library home page.
  9. */
  10. #include <boost/flyweight.hpp>
  11. #include <boost/flyweight/key_value.hpp>
  12. #include <boost/flyweight/no_tracking.hpp>
  13. #include <boost/noncopyable.hpp>
  14. #include <iostream>
  15. using namespace boost::flyweights;
  16. /* Memoized calculation of Fibonacci numbers */
  17. /* This class takes an int n and calculates F(n) at construction time */
  18. struct compute_fibonacci;
  19. /* A Fibonacci number can be modeled as a key-value flyweight
  20. * We choose the no_tracking policy so that the calculations
  21. * persist for future use throughout the program. See
  22. * Tutorial: Configuring Boost.Flyweight: Tracking policies for
  23. * further information on tracking policies.
  24. */
  25. typedef flyweight<key_value<int,compute_fibonacci>,no_tracking> fibonacci;
  26. /* Implementation of compute_fibonacci. Note that the construction
  27. * of compute_fibonacci(n) uses fibonacci(n-1) and fibonacci(n-2),
  28. * which effectively memoizes the computation.
  29. */
  30. struct compute_fibonacci:private boost::noncopyable
  31. {
  32. compute_fibonacci(int n):
  33. result(n==0?0:n==1?1:fibonacci(n-2).get()+fibonacci(n-1).get())
  34. {}
  35. operator int()const{return result;}
  36. int result;
  37. };
  38. int main()
  39. {
  40. /* list some Fibonacci numbers */
  41. for(int n=0;n<40;++n){
  42. std::cout<<"F("<<n<<")="<<fibonacci(n)<<std::endl;
  43. }
  44. return 0;
  45. }