sum_avg.cpp 916 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Boost.Function library examples
  2. // Copyright Douglas Gregor 2001-2003. Use, modification and
  3. // distribution is subject to the Boost Software License, Version
  4. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // For more information, see http://www.boost.org
  7. #include <iostream>
  8. #include <boost/function.hpp>
  9. void do_sum_avg(int values[], int n, int& sum, float& avg)
  10. {
  11. sum = 0;
  12. for (int i = 0; i < n; i++)
  13. sum += values[i];
  14. avg = (float)sum / n;
  15. }
  16. int
  17. main()
  18. {
  19. // The second parameter should be int[], but some compilers (e.g., GCC)
  20. // complain about this
  21. boost::function<void (int*, int, int&, float&)> sum_avg;
  22. sum_avg = &do_sum_avg;
  23. int values[5] = { 1, 1, 2, 3, 5 };
  24. int sum;
  25. float avg;
  26. sum_avg(values, 5, sum, avg);
  27. std::cout << "sum = " << sum << std::endl;
  28. std::cout << "avg = " << avg << std::endl;
  29. return 0;
  30. }