我有一个stl::vector<int>,我需要删除给定索引处的所有元素(向量通常具有高维度).我想知道,考虑到原始矢量的顺序应该保留,这是进行这种操作的最有效方法.
虽然,我在这个问题上发现了相关的帖子,但有些人需要删除一个单元素或多个元素,其中删除 - 删除成语似乎是一个很好的解决方案.但是,在我的情况下,我需要删除多个元素,因为我使用的是索引而不是直接值,remove-erase idiom所以无法应用,对吧?我的代码如下所示,我想知道在效率方面是否可以做得更好?
bool find_element(const vector<int> & vMyVect, int nElem){
return (std::find(vMyVect.begin(), vMyVect.end(), nElem)!=vMyVect.end()) ? true : false;
}
void remove_elements(){
srand ( time(NULL) );
int nSize = 20;
std::vector<int> vMyValues;
for(int i = 0; i < nSize; ++i){
vMyValues.push_back(i);
}
int nRandIdx;
std::vector<int> vMyIndexes;
for(int i = 0; i < 6; ++i){
nRandIdx = rand() % nSize;
vMyIndexes.push_back(nRandIdx);
}
std::vector<int> vMyResult;
for(int i=0; i < (int)vMyValues.size(); i++){ …Run Code Online (Sandbox Code Playgroud) 我有一个基本上由向量矩阵组成的类:vector< MyFeatVector<T> > m_vCells,其中外部向量表示矩阵。这个矩阵中的每个元素都是一个vector(我扩展了stl vector类并将其命名为MyFeatVector<T>)。
我正在尝试编写一种有效的方法来将此类的对象存储在二进制文件中。到目前为止,我需要三个嵌套循环:
foutput.write( reinterpret_cast<char*>( &(this->at(dy,dx,dz)) ), sizeof(T) );
wherethis->at(dy,dx,dz)检索dz向量在位置的元素[dy,dx]。
是否有可能在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++){ …Run Code Online (Sandbox Code Playgroud)