微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vectorXd from_json?

如何解决vectorXd from_json?

我正在尝试使用eigen :: VectorXd和nlohmann-json库实现类的json序列化。将类存储为JSON字符串不是问题。如何从JSON解析VectorXd?还有其他更适合此任务的库吗?

#include "json.hpp"

class TransformationStep {
public:
  VectorXd support_vector;
  int number;

  TransformationStep(int number_param,VectorXd support_vectorParam) {
    number = number_param;
    support_vector = support_vectorParam;
  }

  ~TransformationStep() {
  }

  //json serialization
  void to_json(nlohmann::json &j);
  void from_json(const nlohmann::json &j);
};


void TransformationStep::to_json(nlohmann::json &j) {
  j["number"] = number;
  j["support_vector"] = support_vector;
}


void Ftf::from_json(const nlohmann::json &j)
{
    number = (j.at("number").get<int>());
    //support_vector = j["support_vector"].get<VectorXd>()); //???
}

------输出调用to_json(nlohmann :: json&j)------

{
  "number": 3,"support_vector": [
    -0.00036705693279489064,0.020505439899631835,0.3531380358938106,0.0017673029092790872,-0.9333248513057808,0.04670404618976708,-0.21905858722244081,-1.011945322347849,-0.09172040021815037,0.008526811888809391,0.05187648010664058
  ]
}

解决方法

我想出了

void vector_from_json(VectorXd& vector,const nlohmann::json &j) {
  vector.resize(j.size());
  size_t element_index=0;
  for (const auto& element : j) {
    vector(element_index++) = (double) element;
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。