guide_custom_accumulators_1.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2018 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //[ guide_custom_accumulators_1
  7. #include <boost/format.hpp>
  8. #include <boost/histogram.hpp>
  9. #include <cassert>
  10. #include <iostream>
  11. #include <sstream>
  12. int main() {
  13. using namespace boost::histogram;
  14. using mean = accumulators::mean<>;
  15. // Create a 1D-profile, which computes the mean of samples in each bin.
  16. auto h = make_histogram_with(dense_storage<mean>(), axis::integer<>(0, 2));
  17. // The factory function `make_profile` is provided as a shorthand for this, so this is
  18. // equivalent to the previous line: auto h = make_profile(axis::integer<>(0, 2));
  19. // An argument marked as `sample` is passed to the accumulator.
  20. h(0, sample(1)); // sample goes to first cell
  21. h(0, sample(2)); // sample goes to first cell
  22. h(1, sample(3)); // sample goes to second cell
  23. h(1, sample(4)); // sample goes to second cell
  24. std::ostringstream os;
  25. for (auto&& x : indexed(h)) {
  26. // Accumulators usually have methods to access their state. Use the arrow
  27. // operator to access them. Here, `count()` gives the number of samples,
  28. // `value()` the mean, and `variance()` the variance estimate of the mean.
  29. os << boost::format("index %i count %i mean %.1f variance %.1f\n") % x.index() %
  30. x->count() % x->value() % x->variance();
  31. }
  32. std::cout << os.str() << std::flush;
  33. assert(os.str() == "index 0 count 2 mean 1.5 variance 0.5\n"
  34. "index 1 count 2 mean 3.5 variance 0.5\n");
  35. }
  36. //]