【问题标题】:c++ nlohmann json saving 2d arrayc++ nlohmann json保存二维数组
【发布时间】:2021-12-25 09:06:08
【问题描述】:
struct MyStruct {
    Items item[100][60];
    string Something;
    int X;
    int Y;
};

我有这个结构“MyStruct”,它有一个 100 * 60 的二维数组。 如果我想在 Json Array 中为 item[100][60] 保存结构 我如何使用 nlohmann json 来做到这一点? 谁能帮帮我? 或者,如果有一种方法可以在不使用 boost 的情况下保存为二进制文件,我也会采用。

void Save(std::string name, MyStruct test) {
    std::string filename = name + ".dat";
    std::ofstream out(filename);
    boost::archive::binary_oarchive binary_output_archive(out);
    binary_output_archive& test;
    out.close();
}

void Read(std::string filename) {
    std::ifstream in(filename + ".dat");
    boost::archive::binary_iarchive binary_input_archive(in);
    MyStruct test;
    binary_input_archive& test;
    in.close();
}

我试过了,但有时它也会崩溃,所以我想要一个更好的方法

【问题讨论】:

  • 你在问两个不同的问题,要么你想要一个 JSON 对象,要么你想要序列化 ​​MyStruct - 它是什么?
  • 将 MyStruct x , y , items[100][60] 值保存在 json 文件中

标签: c++ arrays json mapping 2d


【解决方案1】:
void Save(const std::string& name, const MyStruct& test) {
    auto result = nlohmann::json{
        {"item", json::array()},
        {"Something", test.Something}
        {"X", test.X},
        {"Y", test.Y},
    };

    for (auto i = 0u; i < 100u; ++i) {
        auto& outer = result["item"];
        for (auto j = 0u; j < 60u; ++j) {
            // You'll need to convert whatever Items is into a JSON type first
            outer[i].push_back(test[i][j]);
        }
    }

    auto out = std::ofstream out(name + ".dat");
    out << result;
}

这样的东西就足够保存了,你可以从这个和the docs中计算出反序列化。

强烈建议您不要使用Items item[100][60],堆栈不适用于那么大的项目。使用std::arrays 的向量来使用堆,但保留相同的内存布局。

【讨论】:

  • 我应该用什么?我正在为我的游戏添加寻路
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 2020-12-04
相关资源
最近更新 更多