我正在尝试进行一些快速而肮脏的 vector 序列化,但它没有按预期工作。问题是尝试从文件中读取 vector 时出现段错误。我将文件偏移量和 vector 大小存储在 header 中。这是代码:
// 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
做事。如果您想获得为 vector 分配的内存的大小(以字节为单位),您可以执行 index.size() * sizeof(size_t)
。 index.size()
是 vector 中元素的个数,sizeof(size_t)
是 vector 中一个元素的大小。
更正后的代码更像是(修剪多余的东西):
// 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)
的真正作用,它返回实际 vector 对象的大小。 vector 存储的元素与其大小是分开的。例如:
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++ - 将 vector 写入文件并读回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13546743/