gpt4 book ai didi

c++ - 如何使用整数作为键/名称将成员添加到 rapidjson 文档?

转载 作者:行者123 更新时间:2023-11-30 01:46:21 28 4
gpt4 key购买 nike

我正在使用 for 循环并希望在向文档添加成员时使用迭代器 i 作为键/名称。例如,我希望文档看起来像这样:

{"1":"123.321","2":"456.654"}

这是我到目前为止尝试过的方法。

<强>1。将 i 转换为 const char*

rapidjson::Value newDouble(6);
for(int i = 0;i<laserScan.size();i++){
newDouble.SetDouble(laserScan[i]);
const char* index = std::to_string(i).c_str();
d.AddMember(index,newDouble,d.GetAllocator());
}

这会生成一个编译器错误,告诉我 AddMember 只能接受 rapidjson::GenericValue& 类型的参数:

error: no matching function for call to ‘rapidjson::GenericDocument<rapidjson::UTF8<> >::AddMember(const char*&, rapidjson::Value&, rapidjson::MemoryPoolAllocator<>&)’
d.AddMember(index,newDouble,d.GetAllocator());//add this name-value pair to the JSON string

<强>2。使用 rapidjson 类型将 i 转换为字符串

rapidjson::Value newDouble(6), newStringIndex(5);
for(int i = 0;i<laserScan.size();i++){
newDouble.SetDouble(laserScan[i]);
const char* index = std::to_string(i).c_str();
size = (rapidjson::SizeType)std::strlen(index);
newStringIndex.SetString(rapidjson::StringRef(index,size));
d.AddMember(newStringIndex,newDouble,d.GetAllocator());
}

这会从 Writer 类中引发以下运行时错误:

Assertion `!hasRoot_' failed.

为什么我很困惑

解决方案 #1 不应该与执行以下操作相同吗?

d.AddMember("1",newDouble,d.GetAllocator());    

这在我尝试时有效,但我不明白为什么无法将整数转换为 const char*。

最佳答案

虽然您已经找到了解决方法,但我想说明一下为什么原始解决方案不起作用。

解决方案#1 的问题是,index 指针在退出作用域时无效。

tutorial 中所述,您可以使用分配器创建一个键字符串来复制它:

std::string s = std::to_string(i)
Value index(s.c_str(), s.size(), d.GetAllocator()); // copy string
d.AddMember(index, newDouble, d.GetAllocator());

对于您的解决方法,您可以简单地:

dataArray.PushBack(laserScan[i], allocator);

关于c++ - 如何使用整数作为键/名称将成员添加到 rapidjson 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335892/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com