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:
&matrix[i]
will give you a pointer to avector<uint32_t>
object. If you want a pointer to that vector's contained data, use&matrix[i][0]
.sizeof(matrix[i])
is the size of the vector object itself, not its contents. Usematrix[i].size()
to get the number of elements.Instead of
sizeof(uint32_t * x)
, usesizeof(uint32_t) * x
.The second
for
loop isn't actually nested in the firstfor
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)
精彩评论