boost :仅迭代 ptree 的元素
这应该很简单(我只是在学习 boost,所以我错过了一些东西)
我已经使用 json_read 读取了一些简单的 JSON,现在有了一个 ptree。网络上的所有示例都显示使用 ptree.get("entry_name") 来获取条目。我想做的就是:
ptree pt;
read_json(ss,pt);
BOOST_FOREACH(ptree::value_type &v, pt)
{
std::cout << v.{entry_name} << v.{value}
}
即循环遍历 ptree 并写出每个名称(即您放入 pt.get() 的内容)及其相应的值。
抱歉,如果这很简单,
罗斯
This should be simple (I'm just learning boost so I'm missing something)
I have read in some simple JSON using json_read and now have a ptree. All the examples on the web show using ptree.get("entry_name") to obtain an entry. All I want to do is something like:
ptree pt;
read_json(ss,pt);
BOOST_FOREACH(ptree::value_type &v, pt)
{
std::cout << v.{entry_name} << v.{value}
}
i.e. loop through the ptree and write out each name (i.e. what you put into pt.get()) and it's corresponding value.
Sorry if this is simple
Ross
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我正在寻找同样的东西,但在任何地方都找不到答案。结果确实非常简单:
iter->first
是条目名称,iter->second.data()
是第一个的条目值等级。 (然后您可以使用iter->second.begin()
/end()
重新迭代以达到更深层次。)此外,如果此迭代中的一个此类节点是不是终端节点,它本身就是一个 ptree,您可以从此迭代器本身将其作为 ptree 获取:
ptree subPt = iter->second.get_child("nodeName");
I was searching the same thing, and couldn't find the answer anywhere. It turned out to be pretty simple indeed:
iter->first
is the entry name, anditer->second.data()
is the entry value of the first level. (You can then re-iterate withiter->second.begin()
/end()
for deeper levels.)Further, if one such node in this iteration is not a terminal node and is itself a ptree, you can get that as ptree from this iterator itself :
ptree subPt = iter->second.get_child("nodeName");
我在 ptree 方面也遇到了麻烦,但这也许可以帮助:
查看 boost 的 ptree 快速教程
和
可以吗?
I'm having troubles with ptree as well, but perhaps this can help:
Check out boost's ptree quick tutorial
and
Would that work?
这是如何使用 BOOST_FOREACH 迭代 ptree 的一个很好的示例
http://akrzemi1.wordpress.com/2011/07/ 13/parsing-xml-with-boost/
使用普通的“get”函数直接访问,请查看 boost 的示例:
http://www.boost.org/doc/libs /1_51_0/doc/html/boost_propertytree/tutorial.html
文档页面位于此处:
http://www.boost.org/doc /libs/1_51_0/doc/html/boost/property_tree/basic_ptree.html
我知道它没有很好的记录,但它很有帮助。
Here's a great example of how to iterate a ptree using BOOST_FOREACH
http://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/
for direct access using the normal "get" functions look at the example from boost:
http://www.boost.org/doc/libs/1_51_0/doc/html/boost_propertytree/tutorial.html
the documentation page is located here:
http://www.boost.org/doc/libs/1_51_0/doc/html/boost/property_tree/basic_ptree.html
I know its not very well documented but it is helpful.
旧线程,但这是 mr_georg's 的 C++11 版本,带有基于范围的 for 循环:
对于此 json :
输出:
Old thread, but here's a C++11 version of mr_georg's answer with range-based for loops:
For this json:
It outputs:
此示例迭代一个简单的 JSON 对象并将其值放入向量中。
This example iterates over a simple JSON object and puts its values into a vector.