[英]Writing a vector to a file and reading it back
我正在尝试做一些快速和脏的矢量序列化,这不能按预期工作。 尝试从文件中读取向量时,问题是段错误。 我将文件偏移量和矢量大小存储在标题中。 这是代码:
// writing
std::vector<size_t> index;
header.offset = ofs.tellp();
header.size = sizeof(index);
ofs.write((char *) &index[0], sizeof(index)); // pretty bad right, but seems to work
// reading
std::vector<size_t> index;
index.resize(header.numElements)
ifs.seekg(header.offset);
// segfault incoming
ifs.read((char *) &index[0], header.size);
说实话,如果这有效,我会感到惊讶,但我不确定什么是实现我想要的正确方法。 我宁愿远离提升,但我已经在使用Qt,所以如果QVector或QByteArray会以某种方式帮助我,我可以使用它们。
sizeof
没有做你认为它对vector
做的事情。 如果要获取向量的已分配内存的大小(以字节为单位),可以执行index.size() * sizeof(size_t)
。 index.size()
是向量中元素的数量, sizeof(size_t)
是向量中一个元素的大小。
更正的代码更像(修剪额外的东西):
// writing...
std::vector<size_t> index;
size_t numElements = index.size();
size_t numBytes = numElements * sizeof(size_t); // get the size in bytes
ofs.write((char *) &index[0], numBytes);
// reading...
std::vector<size_t> index;
index.resize(numElements);
ifs.read((char *) &index[0], numBytes); // again, numBytes is numElements * sizeof(size_t)
至于sizeof(index)
实际上是什么,它返回实际矢量对象的大小。 矢量存储的元素与其大小分开。 例如:
int* array = new int[500];
// sizeof(array) is the size of the pointer, which is likely 4 or 8 bytes if you're on 32 or 64 bit system
我会尝试使用指向矢量的指针。 您正在尝试使用对数据类型的引用。 如果你的C ++试图成为类型安全的话,它可能不起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.