微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C++ 和 RapidJson:在没有文档的情况下定义值

如何解决C++ 和 RapidJson:在没有文档的情况下定义值

我正在使用 RapidJson 在我的 C++ 应用程序中解析 Json 文件

在我的 json 文件中有一个浮点值数组:threshs = [0.2,0.3]。 此数组存储为 Settings 类的属性。类型为 const Value*。如果我需要访问数据,我可以调用 (*settings->threshs)[i].GetFloat()

如果解析时出现错误,我想使用 Settings.h 中设置的认值。这对 Floats,Integers,bools... 很顺利。 问题是:如何在不创建文档的情况下手动创建 const Value*。所以在我的头文件中我想要 s.th。喜欢:

const Value* = {0.2,0.3};

这可能吗? 我唯一的解决方案是将 thresh 的类型更改为向量,并在解析时循环遍历 json 数组并将值复制到向量中

解决方法

此代码在我的设置中编译/运行没有问题:

#include <iostream>

#include <rapidjson/allocators.h>
#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/rapidjson.h>

int main()
{
    using namespace std;
    using namespace rapidjson;

    Value val(kArrayType);

    //{
    MemoryPoolAllocator alloc;
    val.PushBack(Value(0.1).Move(),alloc);
    val.PushBack(Value(0.2).Move(),alloc);
    //}

    Document doc;
    doc.SetObject().AddMember("arr",val,doc.GetAllocator());

    StringBuffer sb;
    PrettyWriter<StringBuffer> writer(sb);
    doc.Accept(writer);
    cout << sb.GetString() << endl;

    return 0;
}

输出:

{
    "arr": [
        0.1,0.2
    ]
}

顺便说一句,如果您取消对 {} 的注释,分配器将在您添加 Value 之前被销毁,这就是您将得到的:

{
    "arr": [
        null,null
    ]
}

从好的方面来说,它不会崩溃。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。