如何返回一个boost::property_tree的叶节点

How return leaf nodes of a boost::property_tree

本文关键字:property tree 叶节点 boost 何返回 返回 一个      更新时间:2023-10-16

我有一个属性树,所有数据都存储在它的叶节点中。然而,这棵树有一个复杂的结构。我现在要做的是:

  1. 获取树的所有(且仅)叶节点,因为它们包含数据和
  2. 召回通向相应叶节点的路径

最后,我想接收所有(且仅是)叶节点的键/值对,其中键包含到节点的完整路径,值包含节点的值。

我的问题是:

  1. 是否有比递归迭代整个树更方便的方法,存储各自的路径并读出没有子节点的值(即"get_leaves()"函数)?
  2. 如果我有一个指向子树的指针(ptree变量,迭代器,无论…)的给定树,是否有一种方法可以轻松确定该子树在树中的相对路径?

我只写一些辅助函数。它们真的没有那么难。下面是一个完全通用的树访问函数,它可选地接受一个谓词:

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);
}

可以与

这样的谓词一起使用
#include <boost/property_tree/ptree.hpp>
bool is_leaf(boost::property_tree::ptree const& pt) {
    return pt.empty();
}

这里有一个简单的演示:

Live On Coliru

#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 == &current) 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;
}

和一个演示Live On Coliru

std::cout << "Path from node: " << path_of(pt, pt.get_child("for.the.sake")) << "n";