LArSoft  v09_90_00
Liquid Argon Software toolkit - https://larsoft.org/
MakeIndex.h
Go to the documentation of this file.
1 
8 #ifndef LARDATA_UTILITIES_MAKEINDEX_H
9 #define LARDATA_UTILITIES_MAKEINDEX_H
10 
11 namespace util {
12 
42  template <typename Coll, typename KeyOf>
43  std::vector<size_t> MakeIndex(Coll const& data, KeyOf key_of = KeyOf())
44  {
45 
46  // we start the index with the best guess that all the items will have
47  // a unique key and they are contiguous:
48  // the index would have the same size as the data
49  std::vector<size_t> Index(data.size(), std::numeric_limits<size_t>::max());
50 
51  size_t min_size = 0; // minimum size needed to hold all keys
52 
53  size_t iDatum = 0;
54  for (auto const& datum : data) {
55  size_t key = size_t(key_of(datum));
56  if (key >= min_size) min_size = key + 1;
57  if (Index.size() <= key) {
58  // make room for the entry: double the size
59  Index.resize(std::max(key + 1, Index.size() * 2), std::numeric_limits<size_t>::max());
60  } // if expand index
61  Index[key] = iDatum;
62  ++iDatum;
63  } // for datum
64  Index.resize(min_size);
65  return Index;
66  } // MakeIndex()
67 
95  template <typename Coll, typename KeyOf>
96  auto MakeMap(Coll const& data, KeyOf key_of = KeyOf())
97  -> std::vector<decltype(key_of(*(data.begin()))) const*>
98  {
99  using Mapped_t = decltype(key_of(*(data.begin())));
100  using Ptr_t = Mapped_t const*;
101  using Map_t = std::vector<Ptr_t>;
102 
103  // we start the index with the best guess that all the items will have
104  // a unique key and they are contiguous:
105  // the index would have the same size as the data
106  Map_t Index(data.size(), nullptr);
107 
108  size_t min_size = 0; // minimum size needed to hold all keys
109 
110  for (auto const& datum : data) {
111  size_t key = size_t(key_of(datum));
112  if (key >= min_size) min_size = key + 1;
113  if (Index.size() <= key) {
114  // make room for the entry: double the size
115  Index.resize(std::max(key + 1, Index.size() * 2), nullptr);
116  } // if expand index
117  Index[key] = &datum;
118  } // for datum
119  Index.resize(min_size);
120  return Index;
121  } // MakeMap()
122 
123 } // namespace util
124 
125 #endif // LARDATA_UTILITIES_MAKEINDEX_H
Namespace for general, non-LArSoft-specific utilities.
Definition: PIDAAlg.h:26
std::vector< size_t > MakeIndex(Coll const &data, KeyOf key_of=KeyOf())
Creates a map of indices from an existing collection.
Definition: MakeIndex.h:43
auto vector(Vector const &v)
Returns a manipulator which will print the specified array.
Definition: DumpUtils.h:289
auto MakeMap(Coll const &data, KeyOf key_of=KeyOf()) -> std::vector< decltype(key_of(*(data.begin()))) const * >
Creates a map of objects from an existing collection.
Definition: MakeIndex.h:96