- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
首先我要说我认为我知道应该怎么做,但是我的代码不会以我尝试的任何方式编译。我的假设基于 this official example of empty ptree trick .在那里你可以找到下一行:
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"))
{
}
但我得到下一个错误:
Error 1 error C2440: 'initializing' : cannot convert from 'std::pair<_Ty1,_Ty2>' to '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>()))
{
}
我明白了:
Error 1 error C2039: 'empty_ptree' : is not a member of 'boost::property_tree'
那我该怎么办:如何迭代 Boost Ptree 并获得子 Ptree?
更新:我也试过这样的代码
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 中可能出了点问题 - 现在我使用该代码得到了正确的结果。
最佳答案
属性树迭代器指向 (key, tree)
类型的 ptree::value_type
对。因此,用于遍历 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++ - Boost 1.46.1,属性树 : How to iterate through ptree receiving sub ptrees?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6656380/
我是一名优秀的程序员,十分优秀!