gpt4 book ai didi

C++ boost ptree 重命名键

转载 作者:太空狗 更新时间:2023-10-29 21:34:50 25 4
gpt4 key购买 nike

在 boost 属性树中,我想将 a.b.c2 等键重命名为 a.b.c3

一种方法是删除节点并用另一个名称放置它的拷贝。问题在于该节点位于其其他兄弟节点的末尾。我更喜欢保持秩序。我该如何修复此代码?

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>

using namespace boost::property_tree;

void print(const ptree &p)
{
json_parser::write_json(std::cout, p);
}

int main()
{
ptree pt0;

pt0.put("a.b.c1",4);
pt0.put("a.b.c2.e1",4);
pt0.put("a.b.c4",2);
pt0.put("a.d",4);
pt0.put("k.m",4);
pt0.put("k.n.as",4);

std::string key_parent="a.b";
std::string full_key="a.b.c2";
std::string full_key2="a.b.c3";
ptree node=pt0.get_child(full_key);
pt0.get_child(key_parent).erase("c2");
pt0.put_child(full_key2,node);

print(pt0);

return 0;
}

结果:(

// before:
{
"a": {
"b": {
"c1": "4",
"c2": {
"e1": "4"
},
"c4": "2"
},
"d": "4"
},
"k": {
"m": "4",
"n": {
"as": "4"
}
}
}


// after:
{
"a": {
"b": {
"c1": "4",
"c4": "2",
"c3": {
"e1": "4"
}
},
"d": "4"
},
"k": {
"m": "4",
"n": {
"as": "4"
}
}
}

最佳答案

您可以使用insertiterator 来执行此操作。

ptree &child = pt0.get_child("a.b");
ptree::iterator it = child.to_iterator(child.find("c2"));
child.insert(it, make_pair("c3", it->second));
child.erase(it);

关于C++ boost ptree 重命名键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45262602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com