使用https://github.com/nlohmann/json,我试图将值分配给一个递归数据结构(json_node_t):故障在C嵌套数据结构++
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
struct json_node_t {
int id;
std::vector<json_node_t> children;
};
void to_json(json& j, const json_node_t& node) {
j = {{"ID", node.id}};
if (!node.children.empty())
j.push_back({"children", node.children});
}
int main() {
json_node_t node_0;
std::vector<int> values = {1,2,3};
std::vector<json_node_t> parents;
parents.resize(20);
for(int i = 0; i < values.size(); i++) {
if (i == 0)
{
node_0.id = values[0];
std::vector<json_node_t> node_children_;
node_0.children = node_children_;
parents[0] = node_0;
} else {
json_node_t node_i;
node_i.id = values[i];
std::vector<json_node_t> node_i_children_;
parents[i] = node_i;
parents[i-1].children.push_back(node_i);
}
}
json j = node_0;
cout << j.dump(2) << endl;
return 0;
}
我的目的是创建如下所示的JSON表示:
{
"ID": 1,
"children": [
{
"ID": 2
},
{
"ID": 3,
"children": []
}
]
}
但是,嵌套的孩子没有打印。我只得到这个输出:
{
"ID": 1
}
有什么问题?我无法将孩子连接到他的父母。我该如何解决这个问题?
注意,[你不能真正做到这一点(https://stackoverflow.com/questions/18672135/why-c-containers-dont-allow-incomplete在当前的C++中。 – juanchopanza
您是否介意将您的问题标题改为对未来有关该特定问题的研究有意义和有用的内容? – user0042