guide_indexed_access.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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_indexed_access
  7. #include <boost/format.hpp>
  8. #include <boost/histogram.hpp>
  9. #include <cassert>
  10. #include <iostream>
  11. #include <numeric> // for std::accumulate
  12. #include <sstream>
  13. using namespace boost::histogram;
  14. int main() {
  15. // make histogram with 2 x 2 = 4 bins (not counting under-/overflow bins)
  16. auto h = make_histogram(axis::regular<>(2, -1.0, 1.0), axis::regular<>(2, 2.0, 4.0));
  17. h(weight(1), -0.5, 2.5); // bin index 0, 0
  18. h(weight(2), -0.5, 3.5); // bin index 0, 1
  19. h(weight(3), 0.5, 2.5); // bin index 1, 0
  20. h(weight(4), 0.5, 3.5); // bin index 1, 1
  21. // use the `indexed` range adaptor to iterate over all bins;
  22. // it is not only more convenient but also faster than a hand-crafted loop!
  23. std::ostringstream os;
  24. for (auto&& x : indexed(h)) {
  25. // x is a special accessor object
  26. const auto i = x.index(0); // current index along first axis
  27. const auto j = x.index(1); // current index along second axis
  28. const auto b0 = x.bin(0); // current bin interval along first axis
  29. const auto b1 = x.bin(1); // current bin interval along second axis
  30. const auto v = *x; // "dereference" to get the bin value
  31. os << boost::format("%i %i [%2i, %i) [%2i, %i): %i\n") % i % j % b0.lower() %
  32. b0.upper() % b1.lower() % b1.upper() % v;
  33. }
  34. std::cout << os.str() << std::flush;
  35. assert(os.str() == "0 0 [-1, 0) [ 2, 3): 1\n"
  36. "1 0 [ 0, 1) [ 2, 3): 3\n"
  37. "0 1 [-1, 0) [ 3, 4): 2\n"
  38. "1 1 [ 0, 1) [ 3, 4): 4\n");
  39. // `indexed` skips underflow and overflow bins by default, but can be called
  40. // with the second argument `coverage::all` to walk over all bins
  41. std::ostringstream os2;
  42. for (auto&& x : indexed(h, coverage::all)) {
  43. os2 << boost::format("%2i %2i: %i\n") % x.index(0) % x.index(1) % *x;
  44. }
  45. std::cout << os2.str() << std::flush;
  46. assert(os2.str() == "-1 -1: 0\n"
  47. " 0 -1: 0\n"
  48. " 1 -1: 0\n"
  49. " 2 -1: 0\n"
  50. "-1 0: 0\n"
  51. " 0 0: 1\n"
  52. " 1 0: 3\n"
  53. " 2 0: 0\n"
  54. "-1 1: 0\n"
  55. " 0 1: 2\n"
  56. " 1 1: 4\n"
  57. " 2 1: 0\n"
  58. "-1 2: 0\n"
  59. " 0 2: 0\n"
  60. " 1 2: 0\n"
  61. " 2 2: 0\n");
  62. }
  63. //]