C++:提升 ptree 相对键
C++: boost ptree relative key
在C++使用来自boost
ptree
时,我需要找到从a.b
访问a.b.c2.e1
的相对键。此密钥为c2.e1
。如何编写一个找到此相对键的函数?
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
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<<relative_key(pt_e1,pt_b)<<std::endl;
return 0;
}
你需要编写一个递归搜索函数,比如:
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;
}
像这样使用它:
住在科里鲁
path_type p = find_subtree(pt_b, pt_e1);
std::cout << p.dump() << std::endl;
打印"c2.e1"。
完整列表
住在科里鲁
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
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;
}
相关文章:
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 如何使用cppcheck处理半相对包含路径
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 使用哈希图进行相对排序
- 有没有办法保证析构函数的相对顺序?
- Windows 和 Linux 之间的相对路径分辨率差异?
- 为什么从具有较大阵列的 SIMD 内部函数中获得的相对加速比标量更大?
- MOVNTI 存储是否相对于由同一线程创建的其他 MOVNTI 存储重新排序?
- 如何获取 CMake 单元测试的相对路径?
- std::atomic 和 std::mutex 的相对性能
- 我如何知道字符串中字符相对于英文字母的位置值?
- 非静态成员引用必须相对于特定对象
- 如何在相对于观看方向的地形中移动
- CRTP相对于抽象类的优势
- 如何设置与其背景图像大小相对应的窗口大小?
- 专门用于"direct"函数类型(与函数指针类型相对)
- 当两个相等的双精度的相对比较不起作用时,我该怎么办?
- 互斥锁能否保护相对于特定指针的数据?
- Bazel:http_archive()中url的相对本地路径
- C++:提升 ptree 相对键