将python字典翻译为C ++ [英] Translating python dictionary to C++
问题描述
我有一个包含以下代码的python代码。
I have python code that contains the following code.
d = {}
d[(0,0)] = 0
d[(1,2)] = 1
d[(2,1)] = 2
d[(2,3)] = 3
d[(3,2)] = 4
for (i,j) in d:
print d[(i,j)], d[(j,i)]
不幸的是,循环遍历python中的所有键并不足以达到我的目的,我想把这段代码翻译成C ++。什么是最好的C ++数据结构用于一个python字典有元组作为其键?什么是C ++等价的上述代码?
Unfortunately looping over all the keys in python isn't really fast enough for my purpose, and I would like to translate this code to C++. What is the best C++ data structure to use for a python dictionary that has tuples as its keys? What would be the C++ equivalent of the above code?
我看了boost库中的稀疏矩阵,但是找不到一个简单的方法循环只有非-zero元素。
I looked at sparse matrices in the boost library, but couldn't find an easy way to loop only over the non-zero elements.
推荐答案
字典将是c ++中的std :: map, std :: pair。
A dictionary would be a std::map in c++, and a tuple with two elements would be a std::pair.
提供的Python代码将转换为:
The python code provided would translate to:
#include <iostream>
#include <map>
typedef std::map<std::pair<int, int>, int> Dict;
typedef Dict::const_iterator It;
int main()
{
Dict d;
d[std::make_pair(0, 0)] = 0;
d[std::make_pair(1, 2)] = 1;
d[std::make_pair(2, 1)] = 2;
d[std::make_pair(2, 3)] = 3;
d[std::make_pair(3, 2)] = 4;
for (It it(d.begin()); it != d.end(); ++it)
{
int i(it->first.first);
int j(it->first.second);
std::cout <<it->second <<' '
<<d[std::make_pair(j, i)] <<'\n';
}
}
这篇关于将python字典翻译为C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!