简体   繁体   English

将矢量写入文件并将其读回

[英]Writing a vector to a file and reading it back

I'm trying to do some quick and dirty vector serialization, which doesn't work as expected. 我正在尝试做一些快速和脏的矢量序列化,这不能按预期工作。 The problem is a segfault when trying to read the vector from a file. 尝试从文件中读取向量时,问题是段错误。 I store the file offset and vector size in the header. 我将文件偏移量和矢量大小存储在标题中。 Here's the code: 这是代码:

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

To be honest I'd surprised if this worked, but I'm not sure what is a proper way to achieve what I want. 说实话,如果这有效,我会感到惊讶,但我不确定什么是实现我想要的正确方法。 I'd prefer to stay away from boost, but I'm already using Qt so if QVector or QByteArray would help me somehow I could use these. 我宁愿远离提升,但我已经在使用Qt,所以如果QVector或QByteArray会以某种方式帮助我,我可以使用它们。

sizeof doesn't do what you think it does for the vector . sizeof没有做你认为它对vector做的事情。 If you want to get the size, in bytes, of the allocated memory for the vector, you can do index.size() * sizeof(size_t) . 如果要获取向量的已分配内存的大小(以字节为单位),可以执行index.size() * sizeof(size_t) index.size() is the number of elements in the vector, and sizeof(size_t) is the size of one element in the vector. index.size()是向量中元素的数量, sizeof(size_t)是向量中一个元素的大小。

The corrected code would be more like (trimming extra stuff): 更正的代码更像(修剪额外的东西):

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

As for what sizeof(index) really does, it returns the size of the actual vector object. 至于sizeof(index)实际上是什么,它返回实际矢量对象的大小。 The elements the vector stores are separate from its size. 矢量存储的元素与其大小分开。 For example: 例如:

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

I would try to use a pointer to a vector. 我会尝试使用指向矢量的指针。 You are trying to use a reference to a data type. 您正在尝试使用对数据类型的引用。 It might not work if your C++ is trying to be typesafe 如果你的C ++试图成为类型安全的话,它可能不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM