guide_custom_accumulators_2.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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_2
  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. // Make a custom accumulator, which tracks the maximum of the samples.
  15. // It must have a call operator that accepts the argument of the `sample` function.
  16. struct maximum {
  17. // return value is ignored, so we use void
  18. void operator()(double x) {
  19. if (x > value) value = x;
  20. }
  21. double value = 0; // value is initialized to zero
  22. };
  23. // Create 1D histogram that uses the custom accumulator.
  24. auto h = make_histogram_with(dense_storage<maximum>(), axis::integer<>(0, 2));
  25. h(0, sample(1.0)); // sample goes to first cell
  26. h(0, sample(2.0)); // sample goes to first cell
  27. h(1, sample(3.0)); // sample goes to second cell
  28. h(1, sample(4.0)); // sample goes to second cell
  29. std::ostringstream os;
  30. for (auto&& x : indexed(h)) {
  31. os << boost::format("index %i maximum %.1f\n") % x.index() % x->value;
  32. }
  33. std::cout << os.str() << std::flush;
  34. assert(os.str() == "index 0 maximum 2.0\n"
  35. "index 1 maximum 4.0\n");
  36. }
  37. //]