LArSoft  v06_85_00
Liquid Argon Software toolkit - http://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  // we start the index with the best guess that all the items will have
46  // a unique key and they are contiguous:
47  // the index would have the same size as the data
48  std::vector<size_t> Index(data.size(), std::numeric_limits<size_t>::max());
49 
50  size_t min_size = 0; // minimum size needed to hold all keys
51 
52  size_t iDatum = 0;
53  for (auto const& datum: data) {
54  size_t key = size_t(key_of(datum));
55  if (key >= min_size) min_size = key + 1;
56  if (Index.size() <= key) {
57  // make room for the entry: double the size
58  Index.resize(
59  std::max(key + 1, Index.size() * 2),
61  );
62  } // if expand index
63  Index[key] = iDatum;
64  ++iDatum;
65  } // for datum
66  Index.resize(min_size);
67  return Index;
68  } // MakeIndex()
69 
70 
98  template <typename Coll, typename KeyOf>
99  auto MakeMap(Coll const& data, KeyOf key_of = KeyOf())
100  -> std::vector<decltype(key_of(*(data.begin()))) const*>
101  {
102  using Mapped_t = decltype(key_of(*(data.begin())));
103  using Ptr_t = Mapped_t const*;
104  using Map_t = std::vector<Ptr_t>;
105 
106  // we start the index with the best guess that all the items will have
107  // a unique key and they are contiguous:
108  // the index would have the same size as the data
109  Map_t Index(data.size(), nullptr);
110 
111  size_t min_size = 0; // minimum size needed to hold all keys
112 
113  for (auto const& datum: data) {
114  size_t key = size_t(key_of(datum));
115  if (key >= min_size) min_size = key + 1;
116  if (Index.size() <= key) {
117  // make room for the entry: double the size
118  Index.resize(std::max(key + 1, Index.size() * 2), nullptr);
119  } // if expand index
120  Index[key] = &datum;
121  } // for datum
122  Index.resize(min_size);
123  return Index;
124  } // MakeMap()
125 
126 } // namespace util
127 
128 
129 #endif // LARDATA_UTILITIES_MAKEINDEX_H
Namespace for general, non-LArSoft-specific utilities.
Definition: PIDAAlg.h:17
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:265
Int_t max
Definition: plot.C:27
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:99