适用于C ++的Python字典列表 [英] Python List of Dictionaries to C++

查看:112
本文介绍了适用于C ++的Python字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要翻译成C ++的Python字典列表.

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}]

我的代码经过精心设计,以便当我寻找例如粒子0的速度,我知道:

My code is designed such that when I look for e.g. velocities of particle 0, I do:

v = myList[0]["v_"+letter]

其中letter是字符串,"A""B",这取决于我拥有的排序函数的输出.我发现这是在Python中实现我的目的的最便捷方法.

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.

我正在尝试将代码转换为C ++(有点新手),但我不知道如何保持类似字典"的功能(即通过可构建的键访问值)连接字符串)和列表的好处,如myList.

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.

我阅读了这个问题,但是没有很成功,无法理解: C ++等效的Python字典列表?

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?

我发现,如果我逐段定义和插入元素,那似乎行得通:

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"];

正确返回10.有没有一种方法可以更有效/更简单地做到这一点?

returns correctly 10. Is there a way to do this more efficient/ in a simpler way?

推荐答案

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

这篇关于适用于C ++的Python字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆