LArSoft  v10_04_05
Liquid Argon Software toolkit - https://larsoft.org/
makeValueIndex.h
Go to the documentation of this file.
1 
13 #ifndef LARCOREALG_COREUTILS_MAKEVALUEINDEX_H
14 #define LARCOREALG_COREUTILS_MAKEVALUEINDEX_H
15 
16 // LArSoft libraries
18 #include "larcorealg/CoreUtils/fromFutureImport.h" // util::pre_std::identity<>
19 
20 // External libraries
21 #include "range/v3/view/enumerate.hpp"
22 
23 // C/C++ standard library
24 #include <cstddef> // std::size_t
25 #include <map>
26 #include <stdexcept> // std::runtime_error
27 #include <string> // std::to_string()
28 #include <type_traits> // std::invoke_result_t, std::remove_reference_t
29 
30 namespace util {
31 
57  template <typename Coll, typename Extractor>
58  decltype(auto) makeValueIndex(Coll const& coll, Extractor getter);
59 
60  template <typename Coll>
61  auto makeValueIndex(Coll const& coll)
62  {
64  }
65 
66 } // namespace util
67 
68 //------------------------------------------------------------------------------
69 //--- template implementation
70 //------------------------------------------------------------------------------
71 template <typename Coll, typename Extractor>
72 decltype(auto) util::makeValueIndex(Coll const& coll, Extractor getter)
73 {
74  using Value_t = typename Coll::value_type;
75  using Key_t = std::remove_reference_t<std::invoke_result_t<Extractor, Value_t>>;
76 
77  using Map_t = std::map<Key_t, std::size_t>;
78 
79  Map_t index;
80  for (auto&& [iValue, collValue] : coll | ranges::views::enumerate) {
81 
82  Key_t const& key = getter(collValue);
83  auto const iKey = index.lower_bound(key);
84  if ((iKey != index.end()) && (iKey->first == key)) {
85  // no guarantee that `key` supports `std::to_string()`: print only indices
86  throw std::runtime_error(std::string(__func__) + ": element #" + std::to_string(iValue) +
87  " has the same key as #" + std::to_string(iKey->second));
88  }
89  index.emplace_hint(iKey, key, iValue);
90  }
91 
92  return index;
93 }
94 
95 //------------------------------------------------------------------------------
96 
97 #endif // LARCOREALG_COREUTILS_MAKEVALUEINDEX_H
Namespace for general, non-LArSoft-specific utilities.
Definition: PIDAAlg.h:26
auto enumerate(Iterables &&...iterables)
Range-for loop helper tracking the number of iteration.
Definition: enumerate.h:49
decltype(auto) constexpr to_string(T &&obj)
ADL-aware version of std::to_string.
Transparent functor that returns its argument just as passed.
Functions to help debugging by instrumenting code.
decltype(auto) makeValueIndex(Coll const &coll, Extractor getter)
Returns a map of value to index.
Code that might appear as standard C++ in the future.