【发布时间】:2011-11-19 11:02:26
【问题描述】:
大家! 我有一个充满无符号字符的二维向量。现在我想将其内容保存到二进制文件中:
std::vector<std::vector<unsigned char> > v2D(1920, std::vector<unsigned char>(1080));
// Populate the 2D vector here
.....
FILE* fpOut;
// Open for write
if ( (err = fopen_s( &fpOut, "e:\\test.dat", "wb")) !=0 )
{
return;
}
// Write the composite file
size_t nCount = 1920 * 1080 * sizeof(unsigned char);
int nWritten = fwrite((char *)&v2D[0][0], sizeof(unsigned char), nCount, fpOut);
// Close file
fclose(fpOut);
但是,当我阅读 test.dat 时,填写一个新的 2D 向量,并将其条目与旧的进行比较。我发现写的内容和原来的不一样。为什么?我的 write 语句有什么问题?你能告诉我如何以正确的方式将二维向量写入二进制文件吗?非常感谢!
#define LON_DATA_ROWS 1920
#define LON_DATA_COLS 1080
std::vector<std::vector<float> > m_fLon2DArray(LON_DATA_ROWS, std::vector<float>(LON_DATA_COLS));
std::ifstream InputFile;
int nSizeOfLonData = TOTAL_LON_ELEMENTS * sizeof(float);
std::vector<char> vLonDataBuffer(nSizeOfLonData);
// Open the file
InputFile.open(m_sNorminalLonLatFile.c_str(), ios::binary);
// Unable to open file pszDataFile for reading
if ( InputFile.fail() )
return false;
// Read longitude data buffer
InputFile.read(&vLonDataBuffer[0], nSizeOfLonData);
// Close the file object
InputFile.close();
// Populate the longitude 2D vector
for (unsigned i = 0; i < LON_DATA_ROWS; i++)
{
memcpy(&m_fLon2DArray[i][0], &vLonDataBuffer[(i * LON_DATA_COLS) * sizeof(float)], LON_DATA_COLS * sizeof(float));
}
// Some operation put here
// Write the results to a binary file
【问题讨论】:
-
长话短说:这不是二维向量,而是向量的向量。 :)
-
为了最好地使用二维数组,您可以汇总自己的小类(包装单个向量并支持 x,y 访问操作),代码应该少于 1 屏幕。或者,如果你喜欢 Boost,你可以使用 boost::multi_array。