увеличить дерево свойств, получая первый элемент

Мне было интересно, есть ли какой-нибудь удобный способ доступа к известному индексу списка с использованием методологии пути.

Метод моей мечты

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]
}
}

0

Решение

Вы должны быть в состоянии получить доступ к диапазону элементов в списке, используя 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 );
}
2

Другие решения

Других решений пока нет …