I have a Python list of dictionaries that I would like to translate to C++.
My list looks more or less like this:
myList = [{"v_A": 5, "v_B": 3}, {"v_A": 1, "v_B":2}, {"v_A":0, "v_B": 0}]
My code is designed such that when I look for e.g. velocities of particle 0, I do:
v = myList[0]["v_"+letter]
where letter
would be a string, "A"
or "B"
, depeding on the output of a sorting function I have. I have found this is the most convenient way to achieve my purpose in Python.
I am trying to translate my code to C++ (being a bit of a newbie) and I don't know how I could keep the "dictionary"-like features (that is, accessing values through a key that can be built concatenating strings) and the benefits the list together like in myList
.
I read this question without much success, being unable to understand: C++ Equivalent of Python List of Dictionaries?
After some research, I thought of a using a vector of unordered maps, but I am unsure on how to define it and work with it. I thought of:
vector< unordered_map <string, int >> myList;
However, I am getting errors all the time. Besides, I don't know how to introduce the values in the dictionaries or access the elements. Am I approaching this from a completely wrong side?
EDIT: I found that if I define and insert the elements piece-wise, it seems to work:
std::vector <unordered_map <string, int> > myList;
unordered_map <string, int> tempMap;
tempMap.insert(std::make_pair("v_A", 10));
myList.push_back(tempMap);
cout << myList[0]["v_A"];
returns correctly 10
. Is there a way to do this more efficient/ in a simpler way?