我有一个Python字典列表,我想翻译成C ++。
我的列表或多或少看起来像这样:
myList = [{"v_A": 5, "v_B": 3}, {"v_A": 1, "v_B":2}, {"v_A":0, "v_B": 0}]
我的代码经过精心设计,因此当我寻找例如粒子0的速度,我知道:
v = myList[0]["v_"+letter]
其中letter
是字符串,"A"
或"B"
,具体取决于我拥有的排序函数的输出。我发现这是在Python中实现我的目的的最便捷方法。
我正在尝试将我的代码转换为C ++(是个新手),但我不知道如何保持类似“字典”的功能(即通过可构建的键访问值)字符串)和列表的共同优势,例如myList
。
我阅读了这个问题,但是没有很成功,无法理解:C++ Equivalent of Python List of Dictionaries?
经过一番研究,我想到了使用无序映射向量的方法,但是不确定如何定义和使用它。我想到了:
vector< unordered_map <string, int >> myList;
但是,我一直都在犯错误。此外,我不知道如何在字典中引入值或访问元素。我是从完全错误的角度来解决这个问题吗?
std::vector<std::unordered_map<std::string, int>> dictList; // This is a list of dicts
std::unordered_map<std::string, int> dict; // Here we create a specific dict we want to add to our list of dicts
dict["key"] = 10; // This is how you add (key, value) pair into dict in c++
dictList.push_back(dict); // This is how you add your dict to the list of dicts