我正在尝试进行一些快速而肮脏的 vector 序列化,这无法按预期进行。问题是尝试从文件中读取 vector 时出现段错误。我将文件偏移量和 vector 大小存储在标题中。这是代码:

// 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/

10-11 22:57
查看更多