File: guide_custom_accumulators_ouroboros.cpp

package info (click to toggle)
boost1.74 1.74.0%2Bds1-21
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 463,588 kB
  • sloc: cpp: 3,338,117; xml: 131,293; python: 33,088; ansic: 14,292; asm: 4,038; sh: 3,353; makefile: 1,193; perl: 1,036; yacc: 478; php: 212; ruby: 102; lisp: 24; sql: 13; csh: 6
file content (51 lines) | stat: -rw-r--r-- 1,649 bytes parent folder | download | duplicates (14)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright 2019 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

//[ guide_custom_accumulators_ouroboros

#include <boost/histogram.hpp>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>

int main() {
  using namespace boost::histogram;

  // First we define the nested histogram type.
  using axis_t = axis::category<int, axis::null_type, axis::option::growth_t>;
  using base_t = histogram<std::tuple<axis_t>>;

  // Now we make an accumulator out of it by using inheritance.
  // We only need to implement operator(). A matching version of operator() is actually
  // present in base_t, but it is templated and this is not allowed by the accumulator
  // concept. Initialization could also happen here. We don't need to initialize anything
  // here, because the default constructor of base_t is called automatically and
  // sufficient for this example.
  struct hist_t : base_t {
    void operator()(const double x) { base_t::operator()(x); }
  };

  auto h = make_histogram_with(dense_storage<hist_t>(), axis::integer<>(1, 4));

  auto x = {1, 1, 2, 2};
  auto s = {1, 2, 3, 3}; // samples are filled into the nested histograms
  h.fill(x, sample(s));

  std::ostringstream os;
  for (auto&& x : indexed(h)) {
    os << x.bin() << " ";
    for (auto&& y : indexed(*x)) { os << "(" << y.bin() << ": " << *y << ") "; }
    os << "\n";
  }

  std::cout << os.str() << std::flush;
  assert(os.str() == "1 (1: 1) (2: 1) \n"
                     "2 (3: 2) \n"
                     "3 \n");
}

//]