gpt4 book ai didi

c++ - 访问 ptree 数组中的特定索引

转载 作者:行者123 更新时间:2023-11-30 03:29:22 26 4
gpt4 key购买 nike

我正在使用 boost 库来操作 JSON 文件,我想访问此 JSON 中数组的特定索引。

boost::property_tree::ptree& jsonfile;
const boost::property_tree::ptree& array =
jsonfile.get_child("my_array");

我想做的是访问存储在索引处的值:

// This code does not compile
int value = array[index].get < int > ("property");

最佳答案

只需使用迭代器对其进行编码:

template <typename T = std::string> 
T element_at(ptree const& pt, std::string name, size_t n) {
return std::next(pt.get_child(name).find(""), n)->second.get_value<T>();
}

如果你想检查索引的边界:

template <typename T = std::string> 
T element_at_checked(ptree const& pt, std::string name, size_t n) {
auto r = pt.get_child(name).equal_range("");

for (; r.first != r.second && n; --n) ++r.first;

if (n || r.first==r.second)
throw std::range_error("index out of bounds");

return r.first->second.get_value<T>();
}

演示

Live On Coliru

#include <boost/property_tree/json_parser.hpp>
#include <iostream>

using boost::property_tree::ptree;

template <typename T = std::string>
T element_at(ptree const& pt, std::string name, size_t n) {
return std::next(pt.get_child(name).find(""), n)->second.get_value<T>();
}

template <typename T = std::string>
T element_at_checked(ptree const& pt, std::string name, size_t n) {
auto r = pt.get_child(name).equal_range("");

for (; r.first != r.second && n; --n) ++r.first;

if (n || r.first==r.second)
throw std::range_error("index out of bounds");

return r.first->second.get_value<T>();
}

int main() {
ptree pt;
{
std::istringstream iss("{\"a\":[1, 2, 3, 4, 5, 6]}");
read_json(iss, pt);
}

write_json(std::cout, pt, false);

// get the 4th element:
std::cout << element_at_checked(pt, "a", 3) << "\n";

// get it as int
std::cout << element_at_checked<int>(pt, "a", 3) << "\n";

// get non-existent array:
try { std::cout << element_at_checked<int>(pt, "b", 0) << "\n"; } catch(std::exception const& e) { std::cout << e.what() << "\n"; }

try { std::cout << element_at_checked<int>(pt, "a", 6) << "\n"; } catch(std::exception const& e) { std::cout << e.what() << "\n"; }
}

打印

{"a":["1","2","3","4","5","6"]}
4
4
No such node (b)
index out of bounds

关于c++ - 访问 ptree 数组中的特定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45753571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com