我有一个类,基本上由向量矩阵组成:
我正在尝试编写一种有效的方法来将此类对象存储在二进制文件中。到目前为止,我需要三个嵌套循环:
是否有任何可能在不使用循环的情况下存储
此外,根据我的嵌套循环实现,将此类对象存储在二进制文件中似乎需要比将相同对象存储在纯文本文件中使用更多的物理空间。这有点奇怪。
我试图遵循http://forum.allaboutcircuits.com/showthread.php?t=16465下的建议,但无法得出适当的解决方案。
谢谢!
以下是我的
vector< MyFeatVector<T> > m_vCells
,其中外部向量表示矩阵。然后该矩阵中的每个元素都是一个vector
(我扩展了stl vector
类并将其命名为MyFeatVector<T>
)。我正在尝试编写一种有效的方法来将此类对象存储在二进制文件中。到目前为止,我需要三个嵌套循环:
foutput.write( reinterpret_cast<char*>( &(this->at(dy,dx,dz)) ), sizeof(T) );
其中this->at(dy,dx,dz)
检索位于[dy,dx]
位置的向量的dz
元素。是否有任何可能在不使用循环的情况下存储
m_vCells
私有成员?我尝试了以下内容:foutput.write(reinterpret_cast<char*>(&(this->m_vCells[0])), (this->m_vCells.size())*sizeof(CFeatureVector<T>));
,但似乎不能正常工作。我们可以假设该矩阵中的所有向量具有相同的大小,尽管也欢迎更一般的解决方案 :-)此外,根据我的嵌套循环实现,将此类对象存储在二进制文件中似乎需要比将相同对象存储在纯文本文件中使用更多的物理空间。这有点奇怪。
我试图遵循http://forum.allaboutcircuits.com/showthread.php?t=16465下的建议,但无法得出适当的解决方案。
谢谢!
以下是我的
serialization
和unserialization
方法的简化示例。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));
//foutput.write(reinterpret_cast<char*>(&(this->m_vCells[0])), nSze*sizeof(CFeatureVector<T>));
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++){
foutput.write( reinterpret_cast<char*>( &(this->at(dy,dx,dz)) ), sizeof(T) );
}
}
}
foutput.close();
return true;
}
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;
}
std::array
),这样你就可以直接输出了呢? - Kerrek SBstd::vector
没有虚析构函数。 - R. Martinho Fernandes