guide_custom_storage.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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_custom_storage
  7. #include <algorithm> // std::for_each
  8. #include <array>
  9. #include <boost/histogram.hpp>
  10. #include <boost/histogram/algorithm/sum.hpp>
  11. #include <functional> // std::ref
  12. #include <unordered_map>
  13. #include <vector>
  14. int main() {
  15. using namespace boost::histogram;
  16. const auto axis = axis::regular<>(10, 0.0, 1.0);
  17. auto data = {0.1, 0.3, 0.2, 0.7};
  18. // Create static histogram with vector<int> as counter storage, you can use
  19. // other arithmetic types as counters, e.g. double.
  20. auto h1 = make_histogram_with(std::vector<int>(), axis);
  21. std::for_each(data.begin(), data.end(), std::ref(h1));
  22. assert(algorithm::sum(h1) == 4);
  23. // Create static histogram with array<int, N> as counter storage which is
  24. // allocated completely on the stack (this is very fast). N may be larger than
  25. // the actual number of bins used; an exception is raised if N is too small to
  26. // hold all bins.
  27. auto h2 = make_histogram_with(std::array<int, 12>(), axis);
  28. std::for_each(data.begin(), data.end(), std::ref(h2));
  29. assert(algorithm::sum(h2) == 4);
  30. // Create static histogram with unordered_map as counter storage; this
  31. // generates a sparse histogram where only memory is allocated for bins that
  32. // are non-zero. This sounds like a good idea for high-dimensional histograms,
  33. // but maps come with a memory and run-time overhead. The default_storage
  34. // usually performs better in high dimensions.
  35. auto h3 = make_histogram_with(std::unordered_map<std::size_t, int>(), axis);
  36. std::for_each(data.begin(), data.end(), std::ref(h3));
  37. assert(algorithm::sum(h3) == 4);
  38. }
  39. //]