getting_started_listing_03.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. // clang-format off
  7. //[ getting_started_listing_03
  8. #include <boost/format.hpp>
  9. #include <boost/histogram.hpp>
  10. #include <cassert>
  11. #include <iostream>
  12. #include <sstream>
  13. int main() {
  14. using namespace boost::histogram;
  15. /*
  16. Create a profile. Profiles does not only count entries in each cell, but
  17. also compute the mean of a sample value in each cell.
  18. */
  19. auto p = make_profile(axis::regular<>(5, 0.0, 1.0));
  20. /*
  21. Fill profile with data, usually this happens in a loop. You pass the sample
  22. with the `sample` helper function. The sample can be the first or last
  23. argument.
  24. */
  25. p(0.1, sample(1));
  26. p(0.15, sample(3));
  27. p(0.2, sample(4));
  28. p(0.9, sample(5));
  29. /*
  30. Iterate over bins and print profile.
  31. */
  32. std::ostringstream os;
  33. for (auto&& x : indexed(p)) {
  34. os << boost::format("bin %i [%3.1f, %3.1f) count %i mean %g\n")
  35. % x.index() % x.bin().lower() % x.bin().upper()
  36. % x->count() % x->value();
  37. }
  38. std::cout << os.str() << std::flush;
  39. assert(os.str() == "bin 0 [0.0, 0.2) count 2 mean 2\n"
  40. "bin 1 [0.2, 0.4) count 1 mean 4\n"
  41. "bin 2 [0.4, 0.6) count 0 mean 0\n"
  42. "bin 3 [0.6, 0.8) count 0 mean 0\n"
  43. "bin 4 [0.8, 1.0) count 1 mean 5\n");
  44. }
  45. //]