C++中二维浮点数组的序列化和反序列化
Serialization and deserialization of two dimensional float array in C++
我有一个结构:
struct Desc {
int rows;
int cols;
}
以及二维浮动阵列。
我需要通过网络传输结构和data
。如何正确地序列化/反序列化它?
这就是我现在所做的:
Desc desc;
desc.rows = 32;
desc.cols = 1024;
float data[rows][cols];
// setting values on array
char buffer[sizeof(Desc)+sizeof(float)*desc.rows*desc.probes];
memcpy(&buffer[0], &desc, sizeof(Desc)); // copying struct into the buffer
memcpy(&buffer[0]+sizeof(Desc), &data, sizeof(float)*rows*probes); // copying data into the buffer
但我不确定这是否是一个正确的方法。
有人能给我一些提示吗?
如果你留在C++中并想提高效率,我会使用Boost Serialization,否则JSON可能是你的朋友。我对这个演示进行了调整,将您的结构序列化为一个文件,但基本上它向流写入/从流读取。
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
struct Desc {
int rows;
int cols;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & rows;
ar & cols;
}
public:
Desc()
{
rows=0;
cols=0;
};
};
int main() {
std::ofstream ofs("filename");
// prepare dummy struct
Desc data;
data.rows=11;
data.cols=22;
// save struct to file
{
boost::archive::text_oarchive out_arch(ofs);
out_arch << data;
// archive and stream closed when destructors are called
}
//...load struct from file
Desc data2;
{
std::ifstream ifs("filename");
boost::archive::text_iarchive in_arch(ifs);
in_arch >> data2;
// archive and stream closed when destructors are called
}
return 0;
}
注意:我还没有检查这个例子是否有效。
*Jost
最好使用NOT二进制序列化。例如:纯文本(std::stringstream)、JSON、XML等
С++示例:
int width = 10;
int height = 20;
float array[height][width];
std::stringstream stream;
stream << width << " " << height << " ";
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
stream << array[i][j] << " ";
}
}
std::string data = stream.str();
// next use the data.data() and data.length()
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理