std::transform 在将 JSON 数组复制到浮点数数组中的使用(C++):

huangapple go评论107阅读模式
英文:

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] }
}

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.0, 3.0 };

    auto dataPtr = std::make_unique<float[]>(3);

    const auto& dataVec = tensor["Data"];
    std::transform(dataVec.cbegin(), dataVec.cend(), dataPtr.get(), [](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

英文:

I have a json array as shown below

{
  { &quot;Data&quot;:[1.0, 2.0, 3.0] }
}

I am trying to copy this json array to a float array using std::transform.

In code -

#include &lt;nlohmann/json.hpp&gt;
#include &lt;memory&gt;

using json = nlohmann::json;
int main(){
    json tensor;
    tensor[&quot;Data&quot;] = { 1.0, 2.0, 3.0 };

    auto dataPtr = std::make_unique&lt;float[]&gt;(3);

    const auto&amp; dataVec = tensor[&quot;Data&quot;];
    std::transform(dataVec.cbegin(), dataVec.cend(), dataPtr, [](float data) { return data; });
}

Error -

cannot increment value of type &#39;std::unique_ptr&lt;float[]&gt;&#39;

Question - How do I use std::transform in this case, where I dont have an iterator

答案1

得分: 3

std::transform可能无法直接增加unique_ptr本身,但您可以获取其中包含的指针。原始指针是可递增的,因此可以用作转换的目标:

std::transform(dataVec.cbegin(), dataVec.cend(), dataPtr.get(), [](float data) { return data; });

英文:

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

huangapple
  • 本文由 发表于 2023年8月4日 21:14:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定