使用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