我在Visual Studio上的C++项目中使用了nlohmann-json,我发现了一个错误
E0349:no operator "=" matches these operands在以下代码中:
#include <nlohmann/json.hpp>
using json = nlohmann::json;
void myFunc(unsigned int** arr) {
json j;
j["myArr"] = arr;//E0349:no operator "=" matches these operands
}出什么问题了?
另一方面,当我尝试下面的方法时,它是有效的。
void myFunc(unsigned int** arr) {
json j;
j["myArr"] = {1,2,3};// no error
}我猜这是由于数据类型问题造成的。
如果能提供任何信息,我将不胜感激。
发布于 2021-03-31 15:22:38
nlohmann json只支持从c++标准库容器创建数组。从指针创建数组是不可能的,因为它没有关于数组大小的信息。
如果您有c++20,那么您可以使用std::span将指针(和大小)转换为容器:
#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而不是原始数组)。
或者手动构造数组(这里仍然需要一个大小):
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]);
}
}https://stackoverflow.com/questions/66882175
复制相似问题