c++ - boost 属性树获取第一个元素

标签 c++ boost boost-propertytree

我想知道是否有一些方便的方法可以使用路径方法访问列表的已知索引。

我的梦想方法

float v = pt.get<float>("root.list[0]);

当前已知的方法(或类似方法)

 ptree::value_type listElement;
 BOOST_FOREACH(listElement,tree.get_child("root.list")){
                return listElement.second.get<float>();
            }

列表格式(json)

{
root:{
 list:[1,2,3,4,5]
}
}

最佳答案

您应该能够使用 boost::property_tree::equal_range 访问列表中的元素范围。使用您正在使用的 JSON 格式,列表中的每个项目都没有关联的名称元素。这意味着有必要在访问范围内的子元素之前获取父节点。

下面的代码是您可以改编的粗略示例:

输入 Json 文件(in.json):

{
    "root" :
    {
        "list" : [1,2,3,4,5]
    }
}

打印列表第n个元素的函数:

void display_list_elem( const ptree& pt, unsigned idx )
{
    // note: the node elements have no name value, ergo we cannot get
    // them directly, therefor we must access the parent node,
    // and then get the children separately

    // access the list node
    BOOST_AUTO( listNode,  pt.get_child("root.list") );


    // get the children, i.e. the list elements
    std::pair< ptree::const_assoc_iterator,
               ptree::const_assoc_iterator > bounds = listNode.equal_range( "" );


    std::cout << "Size of list : " << std::distance( bounds.first, bounds.second ) << "\n";
    if ( idx > std::distance( bounds.first, bounds.second ) )
    {
        std::cerr << "ERROR Index too big\n";
        return;
    }
    else
    {
        std::advance( bounds.first, idx );

        std::cout << "Value @ idx[" << idx << "] = " 
                  << bounds.first->second.get_value<std::string>() << "\n";
    }

    std::cout << "Displaying bounds....\n";
    display_ptree( bounds.first->second, 10 );
}

关于c++ - boost 属性树获取第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13531582/

相关文章:

c++ - 如何在 Windows 上解析由 std::put_time ("%x") 创建的字符串?

c++ - 仅使用 boost 库中的属性树

c++ - boost::property_:tree - 解析和处理数据

c++ - 为数据缺少默认构造函数的链表创建节点

c++ - 当 operator<<() 失败时回退到 to_string()

c++ - 错误 : lvalue required as unary ‘&’ operand

c++ - boost::shared_ptr 需要单个头文件

c++ - 如何在 C++ 中处理或避免堆栈溢出

c++ - 我如何使用 boost::test 和 xcode 4 来测试一些 ios c++ 代码?

c++ - 遍历不包含标签名称的 PTree 子项