我想知道是否有一些方便的方法可以使用路径方法访问列表的已知索引。
我的梦想方法
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/