开发者

QVector size() returning size zero

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&开发者_如何学编程gt; 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 need QVector::resize. The standard C++ vector class works the same way. Reserving space in advance ensures that repeated future calls to append don't have to re-allocate the container's storage all the time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜