在迭代它时从向量中擦除是个坏主意。简单过滤一下。
void function(std::vector <class*> & vector)
{
std::vector <class*>::iterator from= vector.begin();
std::vector <class*>::iterator to= from;
for(; from != vector.end(); ++from)
{
if((*from)->value == 1) continue;
// it should be (*from) or use boost::ptr_vector
*(to++)=*from;
}
vector.erase( to, vector.end() );
Display(vector);
return;
}
这与 Ylisar 的代码完全相同。恕我直言,这对于矢量来说是最好的,如果你总是要删除一些东西,但是如果删除非常罕见(对于整个一个矢量),请使用 Benjamin Lindley 版本。
无论优化是什么,您都可以仅在有要删除的内容时进行过滤:
void function(std::vector <class*> & vector)
{
std::vector <class*>::iterator to= vector.begin();
for(; to != vector.end(); ++to)
{
if((*to)->value == 1)
{
std::vector <class*>::iterator from=to;
for(++from; from != vector.end(); ++from)
{
if((*from)->value == 1) continue;
*(to++)=*from;
}
vector.erase( to, vector.end() );
break;
}
}
Display(vector);
return;
}
如果您不需要保留顺序,则可以从背面复制到最小复制过热:
void function(std::vector <class*> & vector)
{
std::vector <class*>::iterator to= vector.begin();
std::vector <class*>::iterator from=vector.end();
if(to == from) return;
for(;;)
{
if((*to)->value == 1) // need skip value from begin
{
for( --from; from != to; --from)
{
if((*from)->value == 1) continue; // need skip value from end
*to=*from;
++to; // copied, move to next
}
}
else
{
++to; //preserved, move to next
}
if(to == from)
{
vector.erase( to, vector.end() );
break;
}
}
Display(vector);
return;
}