1

我正在尝试做一些快速而肮脏的矢量序列化,但它没有按预期工作。尝试从文件中读取向量时,问题是段错误。我将文件偏移量和矢量大小存储在标题中。这是代码:

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

老实说,如果这行得通,我会感到惊讶,但我不确定什么是实现我想要的正确方法。我宁愿远离 boost,但我已经在使用 Qt,所以如果 QVector 或 QByteArray 能以某种方式帮助我,我可以使用这些。

4

2 回答 2

3

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
于 2012-11-24T23:36:44.197 回答
0

我会尝试使用指向向量的指针。您正在尝试使用对数据类型的引用。如果你的 C++ 试图是类型安全的,它可能不起作用

于 2012-11-24T23:36:29.163 回答