如何用std::transform将JSON数组复制到float数组?解决迭代器报错
问题
我有如下JSON数组:
{ "Data":[1.0, 2.0, 3.0] }
尝试使用std::transform将该JSON数组复制到float数组,编写的C++代码如下:
#include <nlohmann/json.hpp> #include <memory> using json = nlohmann::json; int main(){ json tensor; tensor["Data"] = { 1.0, 2.0, 3.0 }; auto dataPtr = std::make_unique<float[]>(3); const auto& dataVec = tensor["Data"]; std::transform(dataVec.cbegin(), dataVec.cend(), dataPtr, [](float data) { return data; }); }
运行代码时出现错误:
cannot increment value of type 'std::unique_ptr<float[]>'
请问在没有迭代器的情况下,如何正确使用std::transform完成该操作?
解决方法
错误的核心原因是std::unique_ptr<float[]>本身不是迭代器,而std::transform的第三个参数要求是输出迭代器。我们可以通过unique_ptr的get()方法获取指向数组首元素的原始指针,原生指针可以直接当作随机访问迭代器使用,满足std::transform的要求。
另外需要注意两个细节:
- 原代码缺少
<algorithm>头文件,std::transform定义在此头文件中,必须包含才能正常编译。 - nlohmann JSON数组中的数值默认是
double类型,lambda参数最好显式声明为double,再转换为float,避免隐式转换的潜在问题。
修正后的代码如下:
#include <nlohmann/json.hpp> #include <memory> #include <algorithm> using json = nlohmann::json; int main(){ json tensor; tensor["Data"] = { 1.0, 2.0, 3.0 }; auto dataPtr = std::make_unique<float[]>(3); const auto& dataVec = tensor["Data"]; std::transform(dataVec.cbegin(), dataVec.cend(), dataPtr.get(), [](double data) { return static_cast<float>(data); }); }
内容的提问来源于stack exchange,提问作者Nitron_707
相关产品推荐
相关产品推荐

