我正在将perl程序转换为qt/c 。大多数代码都直接转换为C 或QT函数。但是,我不确定如何迁移哈希的perl哈希。
这是我用来组织一些数据
的多级哈希的示例$series{$uid}{$studynum}{$seriesnum}{'exportseriesid'} = $exportseriesid;
$series{$uid}{$studynum}{$seriesnum}{'seriesid'} = $seriesid;
$series{$uid}{$studynum}{$seriesnum}{'subjectid'} = $subjectid;
$series{$uid}{$studynum}{$seriesnum}{'studyid'} = $studyid;
$series{$uid}{$studynum}{$seriesnum}{'modality'} = $modality;
我已经使用Qhash创建单级哈希,例如
QHash<QString, QString> cfg;
int n = cfg["threads"].toInt();
C 中是否有类似的方法?
更新:
我最终使用了嵌套QMAP。QMAP在迭代时会自动通过键对其进行排序,而QHASH则不是。这是我最终使用的代码
/* create a multilevel hash s[uid][study][series]['attribute'] */
QMap<QString, QMap<int, QMap<int, QMap<QString, QString>>>> s;
/* iterate through the UIDs */
for(QMap<QString, QMap<int, QMap<int, QMap<QString, QString>>>>::iterator a = s.begin(); a != s.end(); ++a) {
QString uid = a.key();
/* iterate through the studynums */
for(QMap<int, QMap<int, QMap<QString, QString>>>::iterator b = s[uid].begin(); b != s[uid].end(); ++b) {
int studynum = b.key();
/* iterate through the seriesnums */
for(QMap<int, QMap<QString, QString>>::iterator c = s[uid][studynum].begin(); c != s[uid][studynum].end(); ++c) {
int seriesnum = c.key();
int exportseriesid = s[uid][studynum][seriesnum]["exportseriesid"].toInt();
/* etc... */
}
}
}
您可以使用这样的QHASH:
QHash<QString, QHash<QString, QString>> two_level_hash;
two_level_hash["first_level"]["second_level"] = "your data";
这适用于您想要的水平计数的哈希。
hash/dictionary的直接等效是unordered_map。然后,您可以嵌套它们,就像在Perl示例中一样。这会导致一个可能很难维护的层次结构,就像在脚本语言中推得太远时一样。基本思想
#include<iostream>
#include<string>
#include<unordered_map>
using std::string;
using std::cout;
using std::endl;
int main()
{
typedef std::unordered_map<string, int> bottom;
typedef std::unordered_map<string, bottom> nextlev;
std::unordered_map<string, nextlev> h3d;
h3d["toplev"]["nextlev"]["seriesid"] = 3;
h3d["toplev"]["nextlev"]["subjectid"] = 11;
for (auto k: h3d) {
cout << k.first << " => " << endl;
for (auto k2: k.second) {
cout << "t" << k2.first << " => " << endl;
for (auto k3: k2.second)
cout << "tt" << k3.first << " => " << k3.second << endl;
}
}
return 0;
}
在某些用例中,这可能(或可能不会(表现不佳。您可能需要struct
到组值。对于更多参与和仔细的结构,请参见例如此帖子。
最后,我真的建议将该多级哈希作为课程实现。这也是脚本语言的好主意,当链式数据变得笨拙时:重写为班级。
我对perl
不熟悉,但我怀疑您需要这样的东西:
struct PropertyPath {
QString uid;
QString studynum; // or other type of your preference
QString seriesnum;// or other type of your preference
QString name;
}
uint qHash(const PropertyPath& p, uint seed = 0)
{
auto h = qHash(p.uid, seed);
h = qHash(p.studynum, h);
h = qHash(p.seriesnum, h);
h = qHash(p.name, h);
return h;
}
QHash<PropertyPath, QString> cfg;