关于STL容器删除元素的模板方法
template<class T,class Function>
void EraseFromBy(T& from,Function by)
{
T::iterator iter = from.begin() , prev = iter;
while(iter!=from.end())
{
if(by(*iter))
{
t.erase(iter);
if(prev == iter)
iter = prev = from.begin();
else
{
iter = prev;
iter++;
}
}
else
{
prev = iter;
iter++;
}
}
}
使用方法:
bool ShouldBeDeal(int a) //该函数传递给EraseFromBy,用于做删除的判断选项
{
if(a%2==0)
return true;
return false;
}
void main( void )
{
set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
s.insert(4);
copy(s.begin(),s.end(),ostream_iterator<int>(cout,\"\n\"));
EraseFromBy(s,ShouldBeDeal);
copy(s.begin(),s.end(),ostream_iterator<int>(cout,\"\n\"));
}