c++boostboost-propertytreeequal-range

How is equal_range supposed to work?


#include <boost/property_tree/ptree.hpp>
#include <string>
#include <iostream>

int main()
{
    boost::property_tree::ptree ptree;
    const std::string entry = "server.url";
    ptree.add( entry, "foo.com" );

    auto range = ptree.equal_range( entry );
    for( auto iter = range.first ; iter != range.second ; ++iter )
        std::cout << iter->first << '\n';
}

I don't understand why this code is not printing. As there could be many server.url entries, I was trying to access them using equal_range.


Solution

  • equal_range doesn't work with paths. After the add, your ptree looks like this:

    <root>
      "server"
        "url": "foo.com"
    

    But the equal_range is looking for children named "server.url" directly within the root node.

    Also, you probably want to print out it->second.data(), because the former would just print "server.url" for every found entry.

    Here's the corrected code:

    #include <boost/property_tree/ptree.hpp>
    #include <string>
    #include <iostream>
    
    int main()
    {
        boost::property_tree::ptree ptree;
        const std::string entry = "server.url";
        ptree.add( entry, "foo.com" );
    
        auto range = ptree.get_child("server").equal_range( "url" );
        for( auto iter = range.first ; iter != range.second ; ++iter )
            std::cout << iter->second.data() << '\n';
    }