如何将复数向量转换为指定格式的JSON数组并规范代码格式?
实现复数向量到指定JSON格式的转换(C++)
要将复数向量转换成指定格式的JSON,我们需要借助nlohmann/json库(代码中已引入json.hpp),补充序列化逻辑,把每个std::complex<double>对象转换为包含re(实部)和im(虚部)字段的JSON对象。
修改后的完整代码
#include "json.hpp" #include <iostream> #include <complex> #include <vector> // 为std::complex<double>添加自定义序列化规则 void to_json(nlohmann::json& j, const std::complex<double>& c) { j = nlohmann::json{{"re", c.real()}, {"im", c.imag()}}; } int main() { struct { std::vector<std::complex<double>> Data; } MESSAGE; MESSAGE.Data = {{-3.2, 0.24}, {0.94, -9.3}}; // 将MESSAGE结构体序列化为JSON nlohmann::json output_json; output_json["Data"] = MESSAGE.Data; // 格式化输出JSON std::cout << output_json.dump(4) << std::endl; return 0; }
生成的JSON输出
{ "Data": [ { "re": -3.2, "im": 0.24 }, { "re": 0.94, "im": -9.3 } ] }
内容的提问来源于stack exchange,提问作者Putin_Caput
相关产品推荐
相关产品推荐

