C++에서 계층 적 데이터 구조를 직렬화하고 싶습니다. 내가 일하고있는 프로젝트는 부스트를 사용하므로 내 데이터 노드 구조로 boost::property_tree::ptree
을 사용하고 있습니다.부스트 p 트리를 다른 부스트 p 트리에 노드로 삽입하려면 어떻게해야합니까?
Job
과 같은 하위 수준 구조의 인스턴스를 포함하는 Person
과 같은 상위 수준 구조가 있습니다 (각 사용자는 작업이 있음). Person
및 Job
은 각각 ptreeify
메소드를 구현합니다. 아이디어는 각 객체가 포함하는 서로 다른 객체에 ptreeify
을 호출하도록하여 계층 구조를 직렬화하는 것입니다. 결과 서브 오브젝트의 특성 트리는 포함 오브젝트의 특성 트리에 노드로 삽입됩니다. 문제는 삽입을 실제로 수행하는 방법을 파악할 수 없다는 것입니다.
this SO post 다음은 런타임 오류가 발생합니다. 나는 그것을 일으키는 원인을 이해하는 데 필요한 지식/경험이 부족합니다. 아래 코드를 참조하십시오.
나는 또한 this very similar question을 찾았지만 전혀 대답을 이해하지 못했으며, insert
의 사용으로 인해 합병증이 발생하지 않는다고 생각됩니다.
질문 : 어떻게 다른 속성 트리에 노드로 속성 트리를 삽입합니까?
실제 코드는 다음과 같습니다. 런타임 오류는 Person::ptreeify
안에 발생합니다.
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
using namespace std;
struct Job{
std::string title;
int hoursPerWeek;
ptree ptreeify(void); //return a ptree representing this Job
};
ptree Job::ptreeify(){
ptree pt;
pt.put("title", title);
pt.put("hours", hoursPerWeek);
return pt;
}
struct Person{
std::string name;
Job job;
ptree ptreeify(void); //return a ptree representing this Person
//This must iterively call ptreeify on all sub-objects
void save(const std::string &filename); //write this Person to file
};
ptree Person::ptreeify(){
ptree pt;
pt.put("name", name);
pt.put("job", "");
ptree jobPt;
jobPt = job.ptreeify();
std::cout << "Program dies after this line" << std::endl;
//This next line causes a run time error
pt.insert(pt.get_child("job").begin(), jobPt.begin(), jobPt.end());
return pt;
}
void Person::save(const std::string &filename){
ptree pt;
pt = ptreeify();
write_json(filename, pt);
};
int main(){
Person myPerson;
myPerson.name = "Julius";
Job myJob;
myJob.title = "monkey";
myJob.hoursPerWeek = 40;
myPerson.job = myJob;
myPerson.save("myPerson.dat");
}