Search code examples
c++c++11boostboost-propertytree

C++: boost ptree remove children: no matching function


In an attempt to remove children of a boost property tree, I use a direct node in erase function which lead to

error: no matching function for call to 
‘boost::property_tree::basic_ptree<std::__cxx11::basic_string<char>, 
std::__cxx11::basic_string<char> >::erase(std::pair<const 
std::__cxx11::basic_string<char>, 
boost::property_tree::basic_ptree<std::__cxx11::basic_string<char>, 
std::__cxx11::basic_string<char> > >&)’

at

pt0.erase(pt_child);

What is the correct form of the code?

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

using namespace boost::property_tree;

void print(const ptree &p)
{
    json_parser::write_json(std::cout, p);
}

int main()
{
    ptree pt0;

    for(int i=0;i<10;i++)
        pt0.put_child("kid"+std::to_string(i+1),ptree());
    print(pt0);

    for(auto& pt_child : pt0)
        pt0.erase(pt_child);
    print(pt0);

    return 0;
}

Solution

  • According to docs you can only .erase by key_type or by iterator, but you are trying to do it by value_type.

    You can do either do

    for(auto& [key, data]: pt0)
        pt0.erase(key);
    

    or loop over iterators explicitly:

    for(auto it = pt0.begin(); it != pt0.end(); ++it)
        pt0.erase(it);
    

    But since you are removing all children anyway, a better way would be to just

    pt0.clear();