开发者

Copying to binary file row of a matrix

I want to write each row of a matrix to a binary file. I try writing it like this:

vector< vector<uint32_t> > matrix;开发者_StackOverflow

...

for(size_t i = 0; i < matrix.size(); ++i)
ofile->write( reinterpret_cast<char*>(&matrix[i]), sizeof(uint32_t*sizeof(matrix[i])) );
{
    for(size_t j = 0; j < numcols; ++j)
    {
        std::cout << left << setw(10) << matrix[i][j];
    }
    cout << endl;
}

but it doesn't work, I get garbage numbers.

Any help appreciated,

Ted.


Some issues:

  1. &matrix[i] will give you a pointer to a vector<uint32_t> object. If you want a pointer to that vector's contained data, use &matrix[i][0].

  2. sizeof(matrix[i]) is the size of the vector object itself, not its contents. Use matrix[i].size() to get the number of elements.

  3. Instead of sizeof(uint32_t * x), use sizeof(uint32_t) * x.

  4. The second for loop isn't actually nested in the first for loop. You need to rearrange your braces.


In case interjay's guidelines weren't enough:

vector< vector<uint32_t> > matrix;

for(size_t i = 0; i < matrix.size(); ++i) 
  ofile.write( (char*)&matrix[i][0], sizeof(matrix[i][0])*matrix[i].size() );

Out-of-context question: Why is ofile a pointer? (certainly don't need to be in this example)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜