我已经通读了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,但我被禁止这样做)
发布于 2011-11-18 07:26:59
我认为您必须递归地遍历property_tree。
您可以定义一个在每个节点上递归迭代并为每个节点调用一个方法的函数:
template<typename T>
void traverse_recursive(const boost::property_tree::ptree &parent, const boost::property_tree::ptree::path_type &childPath, const boost::property_tree::ptree &child, T &method)
{
using boost::property_tree::ptree;
method(parent, childPath, child);
for(ptree::const_iterator it=child.begin();it!=child.end();++it) {
ptree::path_type curPath = childPath / ptree::path_type(it->first);
traverse_recursive(parent, curPath, it->second, method);
}
}我们可以定义一个更简单的函数来调用前一个函数:
template<typename T>
void traverse(const boost::property_tree::ptree &parent, T &method)
{
traverse_recursive(parent, "", parent, method);
}现在,您可以修改类A,以便添加一个方法来合并一个节点并填充update_ptree方法:
#include <boost/bind.hpp>
class A {
ptree pt_;
public:
void set_ptree(const ptree &pt) {
pt_ = pt;
}
void update_ptree(const ptree &pt) {
using namespace boost;
traverse(pt, bind(&A::merge, this, _1, _2, _3));
}
ptree get_ptree() {
return pt_;
}
protected:
void merge(const ptree &parent, const ptree::path_type &childPath, const ptree &child) {
pt_.put(childPath, child.data());
}
}; 唯一的限制是可以有几个具有相同路径的节点。它们中的每一个都将被使用,但只有最后一个将被合并。
发布于 2011-11-17 06:03:25
boost.org/doc/libs/1_48_0/doc/html/property_tree/appendices.html:Boost.Property树还不支持这个。看看未来的工作部分。
数学关系: ptree差,并,交。
更新只是一个差异,然后是一个联合。a = (a - b) + b。
一般的解决方案需要递归地遍历update ptree并放置每个叶子。
但是,可以使用put_child构建足够好的解决方案。这可能会完成您需要的所有任务,而不会像一般解决方案那样复杂。
void merge( ptree& pt, const ptree& updates )
{
BOOST_FOREACH( auto& update, updates )
{
pt.put_child( update.first, update.second );
}
}足够好的解决方案有两个限制,巧合的是,它们与ini_parser具有相同的限制。
https://stackoverflow.com/questions/8154107
复制相似问题