如何在遍历list,vector,map时删除符合条件的元素

class  Pred{
public :
    
bool   operator ()( int  a){
        
if (a >= 6 && a <= 7 )
            
return   true ;
        
return   false ;
    }
};
void  f(pair < int , int >  p)
{
    cout
<< p.first << "   " ;
}
int  main(){
    
int  a[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
    list
< int >  b = list < int > ();
    b.assign(a,a
+ 10 );
    vector
< int >  d;
    d.assign(a,a
+ 10 );
    map
< int , int >  c = map < int , int > ();
    
for (list < int > ::iterator it = b.begin();it != b.end();it ++ ){
        c[
* it] =* it;
    }
    
// 删除8,9
     for (list < int > ::iterator it = b.begin();it != b.end();){
        
if ( * it >= 8 &&* it < 10 ){
            it
= b.erase(it);
        }
else {
            it
++ ;
        }
    }
    
// 删除5,6,注意这种写法只适应于list,不适应于vector,因为vector没有remove_if方法
    b.erase(remove_if(b.begin(),b.end(),Pred()),b.end());
    
// 删除3,4
     for (vector < int > ::iterator it = d.begin();it != d.end();){
        
if ( * it >= 3 &&* it <= 4 ){
            it
= d.erase(it);
        }
else {
            it
++ ;
        }
    }

    ostream_iterator < int >  os(cout, "   " );
    copy(b.begin(),b.end(),os);
    cout
<< endl;
    copy(d.begin(),d.end(),os);
    cout
<< endl;
    
// 删除5,6
     for (map < int , int > ::iterator it = c.begin();it != c.end();){
        
if (( * it).first >= 5 && ( * it).first <= 6 ){
            c.erase(it
++ );
        }
        
else {
            it
++ ;
        }
    }
    for_each(c.begin(),c.end(),f);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值