【发布时间】:2011-07-01 15:05:48
【问题描述】:
我有一个基本上由向量矩阵组成的类: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),您可以直接写出来? -
子类化 STL 容器可能是个坏主意。它们不是为子类化而设计的。请注意,例如,
std::vector没有虚拟析构函数。 -
你可能对Boost.Serialization感兴趣。
-
@Kerrek SB,很好的建议,但我需要像我一样考虑私人成员。 @Martinho Fernandes,我不熟悉子类化,由于某些原因我不能使用 boost。你有其他好的网络指针吗?
-
@Peter:我不明白你指的是哪些私人成员。除了矩阵数据之外,您还需要存储任何数据吗?在任何情况下,只需将矩阵数据存储在一维数组中并以适当的步幅访问它。