如何返回一个boost::property_tree的叶节点
How return leaf nodes of a boost::property_tree
我有一个属性树,所有数据都存储在它的叶节点中。然而,这棵树有一个复杂的结构。我现在要做的是:
- 获取树的所有(且仅)叶节点,因为它们包含数据和
- 召回通向相应叶节点的路径
最后,我想接收所有(且仅是)叶节点的键/值对,其中键包含到节点的完整路径,值包含节点的值。
我的问题是:
- 是否有比递归迭代整个树更方便的方法,存储各自的路径并读出没有子节点的值(即"get_leaves()"函数)?
- 如果我有一个指向子树的指针(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 == ¤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;
}
和一个演示Live On Coliru
std::cout << "Path from node: " << path_of(pt, pt.get_child("for.the.sake")) << "n";
相关文章:
- 使用 boost::p roperty_tree::p tree 如何获取特定键的值
- C++模板是否有助于定义单行'property'成员?
- 'QML Connections: Cannot assign to non-existent Property'尽管情况正好相反
- Boost R-Tree中的最小边界矩形计算
- C++ EXC_BAD_ACCESS (Binary Tree)
- Boost::p tree - 访问列表中包含的属性树节点
- Deserilizing n-ary tree
- Balancing KD Tree
- MsiViewFetch "SELECT * FROM `Property`"成功,但返回"Incorrect function." C++
- 如何填充'Tree'结构'Declaratively'
- 为什么qmap使用skiplist而不是ob rb-tree
- Maven User-Agent property and pluginRepository
- 避免在节点中添加重复的子级,使用 Kasper Peeters 的 Tree.hh 库
- SPOJ GSS1 WA - Segment tree
- Flattening the tree
- C++ AVL Tree Deletion
- Boost/Property树确定值类型
- RedBlack and AVL tree c++
- C++中已经有为 LinkedList、HashMap、Tree 等编写的类
- boost::p roperty_:tree - 解析和处理数据