Boost 1.46.1,属性树:如何遍历ptree接收子ptree
Boost 1.46.1, Property Tree: How to iterate through ptree receiving sub ptrees?
首先我要说的是,我认为我得到了它应该如何做,但我的代码不会编译任何方式我尝试。我的假设是基于这个空ptree技巧的官方示例。在那里你可以找到下一行:
const ptree &settings = pt.get_child("settings", empty_ptree<ptree>());
这表明可以(或者应该)从ptree中取出subptree
所以我假设我们可以用BOOST_FOREACH
这样的方式遍历ptree:
BOOST_FOREACH(const boost::property_tree::ptree &v,
config.get_child("servecies"))
{
}
但是我得到下一个错误:
错误1错误C2440: '初始化':无法从'std::pair<_Ty1,_Ty2>'转换为'const boost::property_tree::ptree &'
或者如果我尝试
BOOST_FOREACH(boost::property_tree::ptree &v,
config.get_child("servecies", boost::property_tree::empty_ptree<boost::property_tree::ptree>()))
{
}
我:
错误1错误C2039: 'empty_ptree':不是'boost::property_tree'的成员
那么我该怎么做:如何通过Boost p树迭代并获得子p树?
更新:我也试过这样的代码
BOOST_FOREACH(boost::property_tree::ptree::value_type &v,
config.get_child("path.to.array_of_objects"))
{
std::cout << "First data: " << v.first.data() << std::endl;
boost::property_tree::ptree subtree = (boost::property_tree::ptree) v.second ;
BOOST_FOREACH(boost::property_tree::ptree::value_type &vs,
subtree)
{
std::cout << "Sub data: " << vs.first.data() << std::endl;
}
}
编译,不抛出任何异常,但不计算任何Sub data
,它只是通过这个循环。
更新2:
嗯……我的xml中可能出现了错误-现在我使用该代码得到了正确的结果。
属性树迭代器指向ptree::value_type
类型的形式为(key, tree)
的对。因此,遍历path
节点的子节点的标准循环如下:
BOOST_FOREACH(const ptree::value_type &v, pt.get_child(path)) {
// v.first is the name of the child.
// v.second is the child tree.
}
使用c++ 11,您可以使用以下代码遍历path
节点的所有子节点:
ptree children = pt.get_child(path);
for (const auto& kv : children) {
// kv is of type ptree::value_type
// kv.first is the name of the child
// kv.second is the child tree
}
我在遍历JSON子节点时遇到了同样的问题
boost::property_tree::read_json(streamJSON, ptJSON);
如果你有这样的结构:
{
playlists: [ {
id: "1",
x: "something"
shows: [
{ val: "test" },
{ val: "test1" },
{ val: "test2" }
]
},
{
id: "2"
x: "else",
shows: [
{ val: "test3" }
]
}
]
}
你可以像这样遍历子节点:
BOOST_FOREACH(boost::property_tree::ptree::value_type &playlist, ptJSON.get_child("playlists"))
{
unsigned long uiPlaylistId = playlist.second.get<unsigned long>("id");
BOOST_FOREACH(boost::property_tree::ptree::value_type &show, playlist.second.get_child("shows."))
{
std::string strVal = show.second.get<std::string>("val");
}
}
我找不到任何关于路径选择器"show ."选择子数组的内容。(注意末尾的圆点)
可以在这里找到一些好的文档:http://kaalus.atspace.com/ptree/doc/index.html
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 如何正确地推回然后遍历堆中对象的向量?
- 遍历二维数组的所有子数组
- 如何在可变参数模板函数中遍历可变参数元组?
- 避免在遍历 IShellItemArray 时出现代码重复
- 从特定键开始遍历地图
- 关于链表遍历和调试的困惑
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- Boost 1.46.1,属性树:如何遍历ptree接收子ptree