如何在 c++ 中展平字典

How do I flatten a dictionary in c++

本文关键字:字典 c++      更新时间:2023-10-16

如何展平下面的字典 -

输入:

dict = {
"Key1" : "1",
"Key2" : {
"a" : "2",
"b" : "3",
"c" : {
"d" : "3",
"e" : {
"" : "1"
}
}
}
}

输出:

{
"Key1" : "1",
"Key2.a" : "2",
"Key2.b" : "3",
"Key2.c.d" : "3",
"Key2.c.e" : "1"
}

输入映射的数据类型为map<string, void*>预期的输出映射为map<string,string>

使用 boost PropertyTree。PropertyTree能够表示分层结构,甚至带有一个小的json解析器。它还具有符合 std 的迭代器,因此您可以迭代树并将每个节点复制到输出映射中,从而有效地展平树。

像这样的东西(取自 https://www.boost.org/doc/libs/1_65_1/doc/html/property_tree/tutorial.html(:

namespace pt = boost::property_tree;
ptree tree;
// read the hierarchical data into the tree
pt::read_json(filename, tree);
map<string, string> out;
flatten(tree, out);

其中flatten递归迭代树:

void flatten(const pt::tree &tree, map<string, string> &out)
{
for (const auto &j:tree)
{
copy_to_out(j, out);
if (is_tree(j))
flatten(j, out);
}
}