guide_make_dynamic_histogram.cpp 1.5 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_make_dynamic_histogram
  7. #include <boost/histogram.hpp>
  8. #include <cassert>
  9. #include <sstream>
  10. #include <vector>
  11. const char* config = "4 1.0 2.0\n"
  12. "5 3.0 4.0\n";
  13. int main() {
  14. using namespace boost::histogram;
  15. // read axis config from a config file (mocked here with std::istringstream)
  16. // and create vector of regular axes, the number of axis is not known at compile-time
  17. std::istringstream is(config);
  18. auto v1 = std::vector<axis::regular<>>();
  19. while (is.good()) {
  20. unsigned bins;
  21. double start, stop;
  22. is >> bins >> start >> stop;
  23. v1.emplace_back(bins, start, stop);
  24. }
  25. // create histogram from iterator range
  26. // (copying or moving the vector also works, move is shown below)
  27. auto h1 = make_histogram(v1.begin(), v1.end());
  28. assert(h1.rank() == v1.size());
  29. // with a vector of axis::variant (polymorphic axis type that can hold any one of the
  30. // template arguments at a time) the types and number of axis can vary at run-time
  31. auto v2 = std::vector<axis::variant<axis::regular<>, axis::integer<>>>();
  32. v2.emplace_back(axis::regular<>(100, -1.0, 1.0));
  33. v2.emplace_back(axis::integer<>(1, 7));
  34. // create dynamic histogram by moving the vector
  35. auto h2 = make_histogram(std::move(v2));
  36. assert(h2.rank() == 2);
  37. }
  38. //]