C++ Boost PropertyTree:检查孩子是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7568607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boost PropertyTree: check if child exists
提问by paul23
I'm trying to write an XML parser, parsing the XML file to a boost::property_tree
and came upon this problem. How can I check (quickly) if a child of a certain property exists?
我正在尝试编写一个 XML 解析器,将 XML 文件解析为 aboost::property_tree
并遇到了这个问题。如何(快速)检查某个属性的孩子是否存在?
Obviously I could iterate over all children using BOOST_FOREACH
- however, isn't there a better solution to this?
显然我可以遍历所有使用的孩子BOOST_FOREACH
- 但是,没有更好的解决方案吗?
回答by RobH
optional< const ptree& > child = node.get_child_optional( "possibly_missing_node" );
if( !child )
{
// child node is missing
}
回答by Michael Anderson
Here's a couple of other alternatives:
这里有几个其他的选择:
if( node.count("possibliy_missing") == 0 )
{
...
}
ptree::const_assoc_iterator it = ptree.find("possibly_missing");
if( it == ptree.not_found() )
{
...
}
回答by Mohamed Ali Said
Include this:
包括这个:
#include <boost/optional/optional.hpp>
Remove the const
:
删除const
:
boost::optional< ptree& > child = node.get_child_optional( "possibly_missing_node" );
if( !child )
{
// child node is missing
}
回答by Rich
While these solutions might appear to avoid iterating over the tree, just keep in mind that under the covers they are still doing exactly that, so you are making your algorithm potentially n^2... if you are concerned about performance and have memory to spare, you could use a map container for quick lookups.
虽然这些解决方案似乎避免了对树的迭代,但请记住,在幕后他们仍在这样做,因此您的算法可能是 n^2 ......如果您担心性能并且有内存备用,您可以使用地图容器进行快速查找。