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