I have a class that consists mainly of a matrix of vectors: vector< MyFeatVector<T> > m_vCells , where the external vector is a matrix. Each element in this matrix is ββthen a vector (I extended the stl vector class and named it MyFeatVector<T> ).
I am trying to create an efficient method for storing objects of this class in binary files. So far I need three nested loops:
foutput.write( reinterpret_cast<char*>( &(this->at(dy,dx,dz)) ), sizeof(T) );
where this->at(dy,dx,dz) retrieves the dz element of the vector at the position [dy,dx] .
Is it possible to save the m_vCells private element without using loops? I tried something like: foutput.write(reinterpret_cast<char*>(&(this->m_vCells[0])), (this->m_vCells.size())*sizeof(CFeatureVector<T>)); which seems to be working incorrectly. It can be assumed that all vectors in this matrix are the same size, although a more general solution is also welcomed :-)
In addition, after implementing nested loops, storing objects of this class in binary files requires more physical space than storing the same objects in text files. It's a bit strange.
I tried to follow the suggestion of http://forum.allaboutcircuits.com/showthread.php?t=16465 , but could not come to the right decision.
Thanks!
Below is a simplified example of my serialization and unserialization methods.
template < typename T > bool MyFeatMatrix<T>::writeBinary( const string & ofile ){ ofstream foutput(ofile.c_str(), ios::out|ios::binary); foutput.write(reinterpret_cast<char*>(&this->m_nHeight), sizeof(int)); foutput.write(reinterpret_cast<char*>(&this->m_nWidth), sizeof(int)); foutput.write(reinterpret_cast<char*>(&this->m_nDepth), sizeof(int));
template < typename T > bool MyFeatMatrix<T>::readBinary( const string & ifile ){ ifstream finput(ifile.c_str(), ios::in|ios::binary); int nHeight, nWidth, nDepth; finput.read(reinterpret_cast<char*>(&nHeight), sizeof(int)); finput.read(reinterpret_cast<char*>(&nWidth), sizeof(int)); finput.read(reinterpret_cast<char*>(&nDepth), sizeof(int)); this->resize(nHeight, nWidth, nDepth); for(register int dy=0; dy < this->m_nHeight; dy++){ for(register int dx=0; dx < this->m_nWidth; dx++){ for(register int dz=0; dz < this->m_nDepth; dz++){ finput.read( reinterpret_cast<char*>( &(this->at(dy,dx,dz)) ), sizeof(T) ); } } } finput.close(); return true; }