0
#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.

qdii
  • 12,505
  • 10
  • 59
  • 116

1 Answers1

3

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';
}
Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
  • Alternatively, if there are many server subnodes, each with a url leaf you can apply equal_range to the first level and then extract a child named url at each position – Triskeldeian Dec 14 '19 at 20:52