dzh*_*lil 22 c++ python dictionary tuples
我有python代码,包含以下代码.
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)]
Run Code Online (Sandbox Code Playgroud)
不幸的是,循环遍历python中的所有键并不足以达到我的目的,我想将此代码转换为C++.什么是用于python字典的最佳C++数据结构,它以元组为键?上述代码的C++等价物是什么?
我查看了boost库中的稀疏矩阵,但是找不到一种只在非零元素上循环的简单方法.
Tho*_*mas 39
字典将是c ++中的std :: map,具有两个元素的元组将是std :: pair.
提供的python代码将转换为:
#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';
}
}
Run Code Online (Sandbox Code Playgroud)
类型是
std::map< std::pair<int,int>, int>
Run Code Online (Sandbox Code Playgroud)
将条目添加到地图的代码如下所示:
typedef std::map< std::pair<int,int>, int> container;
container m;
m[ make_pair(1,2) ] = 3; //...
for(container::iterator i = m.begin(); i != m.end(); ++i){
std::cout << i.second << ' ';
// not really sure how to translate [i,j] [j,i] idiom here easily
}
Run Code Online (Sandbox Code Playgroud)
看看Boost.python。它用于 python 和 C++ 之间的交互(基本上使用 C++ 构建 python 库,但也用于在 C++ 程序中嵌入 python)。大多数 python 数据结构和它们的 C++ 等价物都有描述(没有检查你想要的)。