guide_fill_histogram.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2015-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_fill_histogram
  7. #include <boost/histogram.hpp>
  8. #include <cassert>
  9. #include <functional>
  10. #include <numeric>
  11. #include <utility>
  12. #include <vector>
  13. int main() {
  14. using namespace boost::histogram;
  15. auto h = make_histogram(axis::integer<>(0, 3), axis::regular<>(2, 0.0, 1.0));
  16. // fill histogram, number of arguments must be equal to number of axes,
  17. // types must be convertible to axis value type (here integer and double)
  18. h(0, 0.2); // increase a cell value by one
  19. h(2, 0.5); // increase another cell value by one
  20. // fills from a tuple are also supported; passing a tuple of wrong size
  21. // causes an error at compile-time or an assertion at runtime in debug mode
  22. auto xy = std::make_tuple(1, 0.3);
  23. h(xy);
  24. // chunk-wise filling is also supported and more efficient, make some data...
  25. std::vector<double> xy2[2] = {{0, 2, 5}, {0.8, 0.4, 0.7}};
  26. // ... and call fill method
  27. h.fill(xy2);
  28. // once histogram is filled, access individual cells using operator[] or at(...)
  29. // - operator[] can only accept a single argument in the current version of C++,
  30. // it is convenient when you have a 1D histogram
  31. // - at(...) can accept several values, so use this by default
  32. // - underflow bins are at index -1, overflow bins at index `size()`
  33. // - passing an invalid index triggers a std::out_of_range exception
  34. assert(h.at(0, 0) == 1);
  35. assert(h.at(0, 1) == 1);
  36. assert(h.at(1, 0) == 1);
  37. assert(h.at(1, 1) == 0);
  38. assert(h.at(2, 0) == 1);
  39. assert(h.at(2, 1) == 1);
  40. assert(h.at(-1, -1) == 0); // underflow for axis 0 and 1
  41. assert(h.at(-1, 0) == 0); // underflow for axis 0, normal bin for axis 1
  42. assert(h.at(-1, 2) == 0); // underflow for axis 0, overflow for axis 1
  43. assert(h.at(3, 1) == 1); // overflow for axis 0, normal bin for axis 1
  44. // iteration over values works, but see next example for a better way
  45. // - iteration using begin() and end() includes under- and overflow bins
  46. // - iteration order is an implementation detail and should not be relied upon
  47. const double sum = std::accumulate(h.begin(), h.end(), 0.0);
  48. assert(sum == 6);
  49. }
  50. //]