首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >E0349:在使用使用nlohmann-json的JSON时,没有运算符"=“匹配这些操作数

E0349:在使用使用nlohmann-json的JSON时,没有运算符"=“匹配这些操作数
EN

Stack Overflow用户
提问于 2021-03-31 13:32:19
回答 1查看 102关注 0票数 1

我在Visual Studio上的C++项目中使用了nlohmann-json,我发现了一个错误

代码语言:javascript
复制
E0349:no operator "=" matches these operands

在以下代码中:

代码语言:javascript
复制
#include <nlohmann/json.hpp>
using json = nlohmann::json;


void myFunc(unsigned int** arr) {
    json j;
    j["myArr"] = arr;//E0349:no operator "=" matches these operands
}

出什么问题了?

另一方面,当我尝试下面的方法时,它是有效的。

代码语言:javascript
复制
void myFunc(unsigned int** arr) {
    json j;
    j["myArr"] = {1,2,3};// no error
}

我猜这是由于数据类型问题造成的。

如果能提供任何信息,我将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-31 15:22:38

nlohmann json只支持从c++标准库容器创建数组。从指针创建数组是不可能的,因为它没有关于数组大小的信息。

如果您有c++20,那么您可以使用std::span将指针(和大小)转换为容器:

代码语言:javascript
复制
#include <nlohmann/json.hpp>
#include <span>

using json = nlohmann::json;


void myFunc(unsigned int* arr, size_t size) {
    json j;
    j["myArr"] = std::span(arr, size);
}

如果没有c++20,就必须自己实现std::span,或者将数组复制到类似std::vector的文件中(或者直接使用std::vector而不是原始数组)。

或者手动构造数组(这里仍然需要一个大小):

代码语言:javascript
复制
void myFunc(unsigned int* arr, size_t size) {
    json j;
    auto& myArr = j["myArr"];
    for (size_t i = 0; i < size; i++)
    {
        myArr.push_back(arr[i]);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66882175

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档