我已阅读boost :: property_tree的文档,但没有找到更新或合并ptree与另一ptree的方法。我该怎么做呢?如何合并/更新boost :: property_tree :: 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中添加到这个问题,但我不允许)
谢谢。这是一个有趣的解决方案。要编一个看看!但是,什么意思是“可能有几个节点具有相同的路径”? Tree_1 =“a.b.c”= 0更新树Tree_2 =“a.b.c”= 1,“a.b.d”= 2。只会更新“a.b.d”= 2吗? (要调试并查看) – mantler
可能有多个节点具有完全相同的路径。当Tree_1包含“a.b.c”= 1,“a.b.c”= 2且Tree_2包含“a.b.c”= 1时,在用Tree_1更新Tree_2之后,Tree_2将包含“a.b.c”= 2。 –
这是一段非常酷的代码。你是怎么知道这个操作符能工作在path_type?上的:'ptree :: path_type curPath = childPath/ptree :: path_type(it-> first);'我看不到它是在文档中定义的操作符。 – 2NinerRomeo