I have a json array as shown below
{
{ "Data":[1.0, 2.0, 3.0, 4.0] }
}
I am trying to copy this json array to a float array using std::transform.
In code –
#include <nlohmann/json.hpp>
#include <memory>
using json = nlohmann::json;
int main(){
json tensor;
tensor["Data"] = { 1, 0, 2 };
auto dataPtr = std::make_unique<float[]>(3);
const auto& dataVec = tensor["Data"];
std::transform(dataVec.cbegin(), dataVec.cend(), dataPtr, [](float data) { return data; });
}
Error –
cannot increment value of type 'std::unique_ptr<float[]>'
Question – How do I use std::transform in this case, where I dont have an iterator
>Solution :
std::transform may not be able to increment the unique_ptr itself, but you can get the contained pointer. The raw pointer is incrementable, so it is usable as a target for the transform:
std::transform(dataVec.cbegin(), dataVec.cend(), dataPtr.get(), [](float data) { return data; });