问题
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?
Obviously I could iterate over all children using BOOST_FOREACH
- however, isn't there a better solution to this?
回答1:
optional< const ptree& > child = node.get_child_optional( "possibly_missing_node" );
if( !child )
{
// child node is missing
}
回答2:
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() )
{
...
}
回答3:
Include this:
#include <boost/optional/optional.hpp>
Remove the const
:
boost::optional< ptree& > child = node.get_child_optional( "possibly_missing_node" );
if( !child )
{
// child node is missing
}
回答4:
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.
来源:https://stackoverflow.com/questions/7568607/boost-propertytree-check-if-child-exists