复制到vector <unsigned char =“”> </unsigned>中的无类型对象的内容

时间:2014-04-22 09:24:46

标签: c++ bytearray void memcpy

我试图将包含图像字节的无类型对象的内容写入填充了unsigned char的向量中。可悲的是,我无法让它发挥作用。也许有人可以指出我正确的方向?

这就是我现在所拥有的:

vector<unsigned char> SQLiteDB::BlobData(int clmNum){
   //i get the data of the image
   const void* data = sqlite3_column_blob(pSQLiteConn->pRes, clmNum);
   vector<unsigned char> bytes;
   //return the size of the image in bytes
   int size = getBytes(clNum);
   unsigned char b[size];
   memcpy(b, data, size);
   for(int j=0;j<size,j++){
      bytes.push_back(b[j])M
   }
   return bytes;
}

如果我试图追踪字节向量的内容,那么它都是空的。

所以问题是,如何将数据导入向量?

2 个答案:

答案 0 :(得分:9)

你应该使用带有几个迭代器的vector的构造函数:

const unsigned char* data = static_cast<const unsigned char*>(sqlite3_column_blob(pSQLiteConn->pRes, clmNum));
vector<unsigned char> bytes(data, data + getBytes(clNum));

答案 1 :(得分:1)

直接写入vector,无需其他无用的副本:

bytes.resize(size);
memcpy(bytes.data(), data, size);

而不是副本,它具有零初始化,因此使用像Maxim演示的构造函数或vector::insert更好。

const unsigned char* data = static_cast<const unsigned char*>(sqlite3_column_blob(pSQLiteConn->pRes, clmNum));
bytes.insert(data, data + getBytes(clNum));