ppap4lmp  0.7.2
map_to_index.cpp
Go to the documentation of this file.
1 
8 #include "map_to_index.h"
9 #include "runtime_error.h"
10 
11 namespace ut = utils;
12 
13 /* ------------------------------------------------------------------ */
14 
16  const Json &data,
17  const Str &key)
18 {
19  Map<Json,int> tmp;
20 
21  if (data.is_array())
22  {
23  auto &front = data.front();
24  const int key_position = std::distance(front.cbegin(), front.find(key));
25 
26  tmp.reserve(data.size());
27 
28  int index = 0;
29 
30  for (const auto &d : data)
31  {
32  tmp[*std::next(d.cbegin(), key_position)] = index++;
33  }
34  }
35 
36  if (tmp.size() != data.size())
37  {
38  ut::runtime_error("Map to index is not bijection");
39  }
40 
41  return tmp;
42 }
43 
44 /* ------------------------------------------------------------------ */
45 /* Not need for now
46 Map<Json,int> ut::map_to_index(
47  const Json &data,
48  const Vec<Str> &keys)
49 {
50  Map<Json,int> tmp;
51 
52  if (data.is_array())
53  {
54  tmp.reserve(data.size());
55 
56  int index = 0;
57 
58  for (const auto &d : data)
59  {
60  auto array = Json::array();
61 
62  for (const auto &key : keys)
63  {
64  array.push_back(d[key]);
65  }
66 
67  tmp[array] = index++;
68  }
69  }
70 
71  if (tmp.size() != data.size())
72  {
73  ut::runtime_error("Map to index is not bijection");
74  }
75 
76  return tmp;
77 }
78 */
std::string Str
Str is an alias for string.
Definition: std.h:21
nlohmann::json Json
Json is an alias for nlohmann::json.
Definition: json.h:22
void runtime_error(const Str &msg)
Raise (for Python) and throw (for C++) a runtime error.
This file has a definition of utils::map_to_index.
This file has a definition of utils::runtime_error.
Namespace for utility functions.
Definition: join.h:14
std::unordered_map< T, U > Map
Map is an alias for unordered map (same as dict in Python).
Definition: std.h:38
Map< Json, int > map_to_index(const Json &data, const Str &key)
Create a Map object from values of selected property in an array Json object to corresponding index i...