These 2 functions are my attempt to serialize a QVector. Unfortunally I can’t use QDataStream because my boss requires that the implementation is Qt independent and QDataStream prepends a header. So the problem is the vector returned by the function binToVector returns a size equals to 0, but if the elements are printed they are equal to the original vector. Why the size returned is zero if the vector has elements equal to the original? These serialization functions are ok? I cannot use boost neither Qt functions to implement it, only C++;
QByteArray vectorToBin(const QVector<qint32> & vec)
{
QByteArray result;
foreach(quint32 e, vec) {
char *src = reinterpret_cast<char*>(&e);
result.append(src, sizeof(qint32));
}
return result;
}
QVector<qint32> binToVector(const QByteArray & bytes)
{
int size = sizeof(qint32);
QVector<qint32> result;
result.reserve(bytes.count()/size);
int j=0;
for(int i=0; i<bytes.count(); i+=size) {
memcpy(&result[j++], bytes.constData()+i, size);
}
return result;
}
You’re calling
QVector::reserve, which allocates memory for the class to use as storage, but doesn’t actually change the number of real elements in the container. For that, you needQVector::resize. The standard C++vectorclass works the same way. Reserving space in advance ensures that repeated future calls toappenddon’t have to re-allocate the container’s storage all the time.