Imported Upstream version 1.72.0
[platform/upstream/boost.git] / libs / histogram / examples / getting_started_listing_04.cpp
1 // Copyright 2019 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 // clang-format off
8
9 //[ getting_started_listing_04
10
11 #include <algorithm>           // std::max_element
12 #include <boost/format.hpp>    // only needed for printing
13 #include <boost/histogram.hpp> // make_histogram, integer, indexed
14 #include <iostream>            // std::cout, std::endl
15 #include <sstream>             // std::ostringstream
16
17 int main() {
18   using namespace boost::histogram;
19   using namespace boost::histogram::literals;
20
21   /*
22     We make a 3d histogram for color values (r, g, b) in an image. We assume the values
23     are of type char. The value range then is [0, 256). The integer axis is perfect for
24     color values.
25   */
26   auto h = make_histogram(
27     axis::integer<>(0, 256, "r"),
28     axis::integer<>(0, 256, "g"),
29     axis::integer<>(0, 256, "b")
30   );
31
32   /*
33     We don't have real image data, so fill some fake data.
34   */
35   h(1, 2, 3);
36   h(1, 2, 3);
37   h(0, 1, 0);
38
39   /*
40     Now let's say we want to know which color is most common. We can use std::max_element
41     on an indexed range for that.
42   */
43   auto ind = indexed(h);
44   auto max_it = std::max_element(ind.begin(), ind.end());
45
46   /*
47     max_it is a special iterator to the histogram cell with the highest count.
48     This iterator allows one to access the cell value, bin indices, and bin values.
49     You need to twice dereference it to get to the cell value.
50   */
51   std::ostringstream os;
52   os << boost::format("count=%i rgb=(%i, %i, %i)")
53         % **max_it % max_it->bin(0_c) % max_it->bin(1) % max_it->bin(2);
54
55   std::cout << os.str() << std::endl;
56
57   assert(os.str() == "count=2 rgb=(1, 2, 3)");
58 }
59
60 //]