c++ ptree判断是否存在节点_C ++:boost ptree相对键

In C++ using ptree from boost, I need to find the relative key to access a.b.c2.e1 from a.b. This key is c2.e1. How can I write a function which finds this relative key?

#include

#include

#include

using namespace boost::property_tree;

std::string relative_key(const ptree &p1,const ptree &p2)

{

??????????????

// return "b.c2.e1";

}

int main()

{

ptree pt0;

pt0.put("a.b.c1",4);

pt0.put("a.b.c2.e1",4);

pt0.put("a.b.c4",4);

pt0.put("a.d",4);

pt0.put("k.m",4);

pt0.put("k.n",4);

ptree &pt_e1=pt0.get_child("a.b.c2.e1");

ptree &pt_b=pt0.get_child("a.b");

std::cout<

return 0;

}

解决方案

You'd need to write a recursive search function, like:

bool find_subtree_helper(ptree const& haystack, ptree const& needle, path_type& path) {

if (std::addressof(haystack) == std::addressof(needle))

return true;

for (auto& child : haystack) {

auto next = path;

next /= child.first;

if ( std::addressof(child.second) == std::addressof(needle)

|| find_subtree_helper(child.second, needle, next))

{

path = next;

return true;

}

}

return false;

}

path_type find_subtree(ptree const& haystack, ptree const& needle) {

path_type path;

if (!find_subtree_helper(haystack, needle, path))

throw std::range_error("not subtree");

return path;

}

Use it like:

path_type p = find_subtree(pt_b, pt_e1);

std::cout << p.dump() << std::endl;

Which prints "c2.e1".

Full Listing

#include

#include

#include

using namespace boost::property_tree;

using path_type = ptree::path_type;

bool find_subtree_helper(ptree const& haystack, ptree const& needle, path_type& path) {

if (std::addressof(haystack) == std::addressof(needle))

return true;

for (auto& child : haystack) {

auto next = path;

next /= child.first;

if ( std::addressof(child.second) == std::addressof(needle)

|| find_subtree_helper(child.second, needle, next))

{

path = next;

return true;

}

}

return false;

}

path_type find_subtree(ptree const& haystack, ptree const& needle) {

path_type path;

if (!find_subtree_helper(haystack, needle, path))

throw std::range_error("not subtree");

return path;

}

int main()

{

ptree pt0;

pt0.put("a.b.c1",4);

pt0.put("a.b.c2.e1",4);

pt0.put("a.b.c4",4);

pt0.put("a.d",4);

pt0.put("k.m",4);

pt0.put("k.n",4);

ptree &pt_e1 = pt0.get_child("a.b.c2.e1");

ptree &pt_b = pt0.get_child("a.b");

path_type p = find_subtree(pt_b, pt_e1);

std::cout << p.dump() << std::endl;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值