Your issue at hand has little to do with the constness of the iterators, you are simply erasing with the wrong ptree iterator.
ptree& persons = pt.get_child("root.persons");
for(auto it = persons.begin(); it != persons.end();) {
if(it->second.get<string>("name") == "dad")
it = persons.erase(it);
else
++it;
}
The ptree uses a multi_index for sub-nodes, and to keep an iteration stable over erasures, you must use the iterator returned from the erase() operation to continue the iteration, a common pattern.
Note that the XML in the question has an /
(</age>
) termination missing, it wouldn't validate. I am not editing the question to fix it since this could be one of the problems that you experience with the execution of the program.
Output of processing the ptree with the above code via write_xml(std::out, pt)
:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<persons>
<person>
<name>me</name>
<age>4</age>
</person>
</persons>
</root>