我正在利用boost ptree库创建一个JSON字符串,但通过执行以下操作,我发现它很乏味。我需要将像"metric.name" : [A, B]这样的简单数组添加到metrics ptree中。我能做得更好吗?或者至少用一种更干净的方式写这个。
pt::ptree metric_avg;
metric_avg.put("", 9999);
pt::ptree metric_std;
metric_std.put("", 0);
pt::ptree metric_distr;
metric_distr.push_back({"", metric_avg});
metric_distr.push_back({"", metric_std});
metrics.add_child(metric.name, metric_distr);发布于 2021-01-28 13:55:27
我会写一些助手函数
template<typename T>
pt::ptree scalar(const T & value)
{
pt::ptree tree;
tree.put("", value);
return tree;
}
template<typename T>
pt::ptree array(std::initialiser_list<T> container)
{
pt::ptree tree;
for (auto & v : container)
{
tree.push_back(scalar(v));
}
return tree;
}这样你就可以写了
metrics.put(metric.name, array({ 9999, 0 }));发布于 2021-01-29 00:40:11
我会:
住在Coliru
ptree metric_avg;
auto& arr = metric_avg.put_child("metric name", {});
arr.push_back({"", ptree("9999")});
arr.push_back({"", ptree("0")});或住在Coliru
for (auto el : {"9999", "0"})
arr.push_back({"", ptree(el)});甚至是住在Coliru
for (auto el : {9999, 0})
arr.push_back({"", ptree(std::to_string(el))});全都印出来了
{
"metric name": [
"9999",
"0"
]
}https://stackoverflow.com/questions/65936511
复制相似问题