Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::transform in copying data from json array to a float array C++

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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; });

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading