我已经阅读了 boost::property_tree 的文档,但还没有找到一种方法来更新或合并一个 ptree 与另一个 ptree。我该怎么做呢?
给定下面的代码,update_ptree 函数会是什么样子?
#include <iostream>
#include <boost/property_tree/ptree.hpp>
using boost::property_tree::ptree;
class A
{
ptree pt_;
public:
void set_ptree(const ptree &pt)
{
pt_ = pt;
};
void update_ptree(const ptree &pt)
{
//How do I merge/update a ptree?
};
ptree get_ptree()
{
return pt_;
};
};
int main()
{
A a;
ptree pt;
pt.put<int>("first.number",0);
pt.put<int>("second.number",1);
pt.put<int>("third.number",2);
a.set_ptree(pt);
ptree pta = a.get_ptree();
//prints "0 1 2"
std::cout << pta.get<int>("first.number") << " "
<< pta.get<int>("second.number") << " "
<< pta.get<int>("third.number") << "\n";
ptree updates;
updates.put<int>("first.number",7);
a.update_ptree(updates);
pta = a.get_ptree();
//Because the update_tree function doesn't do anything it just prints "0 1 2".
//I would like to see "7 1 2"
std::cout << pta.get<int>("first.number") << " "
<< pta.get<int>("second.number") << " "
<< pta.get<int>("third.number") << "\n";
return 0;
}
我考虑过迭代新的 ptree 并使用“put”来插入值。但是“put”需要一个类型,我不知道如何从新的 ptree 中获取该信息并将其用作旧 ptree 的参数。
我在 update_ptree 函数中尝试过的一件事是使用:
pt_.add_child(".",pt);
基本上我尝试将 pt 作为子级添加到 pt_ 的根目录中。不幸的是,这似乎不起作用。
有任何想法吗?
我很感激任何帮助。
谢谢你。
(我试图将标签 property_tree 和 ptree 添加到这个问题,但我不被允许)