我有一个属性树,其中所有数据都存储在其叶节点中。然而,树具有复杂的结构。我现在想做的是:
最后,我希望接收所有(并且只有)叶子节点的键/值对,其中键包含节点的完整路径,值包含节点的值。
我的问题是:
答案 0 :(得分:3)
我只是写一些辅助函数。他们真的不那么难。这是一个完全通用的树访问函数,可选择使用谓词:
select 1, 167 from ONE_RECORD_DUMMY_TABLE
您可以将其与
之类的谓词一起使用template <typename Tree, typename F, typename Pred/* = bool(*)(Tree const&)*/, typename PathType = std::string>
void visit_if(Tree& tree, F const& f, Pred const& p, PathType const& path = PathType())
{
if (p(tree))
f(path, tree);
for(auto& child : tree)
if (path.empty())
visit_if(child.second, f, p, child.first);
else
visit_if(child.second, f, p, path + "." + child.first);
}
template <typename Tree, typename F, typename PathType = std::string>
void visit(Tree& tree, F const& f, PathType const& path = PathType())
{
visit_if(tree, f, [](Tree const&){ return true; }, path);
}
这是一个简单的演示:
<强> Live On Coliru 强>
#include <boost/property_tree/ptree.hpp>
bool is_leaf(boost::property_tree::ptree const& pt) {
return pt.empty();
}
打印:
#include <iostream>
int main()
{
using boost::property_tree::ptree;
auto process = [](ptree::path_type const& path, ptree const& node) {
std::cout << "leave node at '" << path.dump() << "' has value '" << node.get_value("") << "'\n";
};
ptree pt;
pt.put("some.deeply.nested.values", "just");
pt.put("for.the.sake.of.demonstration", 42);
visit_if(pt, process, is_leaf);
}
<强>更新强>
刚才提到问题的后半部分。以下是使用相同访问者的方法:
leave node at 'some.deeply.nested.values' has value 'just'
leave node at 'for.the.sake.of.demonstration' has value '42'
template <typename Tree>
boost::optional<std::string> path_of_optional(Tree const& tree, Tree const& target) {
boost::optional<std::string> result;
visit(tree, [&](std::string const& path, Tree const& current) { if (&target == ¤t) result = path; });
return result;
}
template <typename Tree>
std::string path_of(Tree const& tree, Tree const& target) {
auto r = path_of_optional(tree, target);
if (!r) throw std::range_error("path_of");
return *r;
}