我已閱讀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