STL中容器的删除操作。

第九条 
1.删除c容器中所有值为1963的元素。

//删除c容器中所有值为1963的元素。

//当c是vector,string,deque时,erase-remove习惯用法是删除特定值元素的最好办法
c.erase(remove(c.begin,c.end,1963),c.end);

//对于list
c.remove(1963);

//对于关联容器
c.erase(1963);

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2.不在从c中删除所有特定值的元素,而是删除使得下列判别式返回true的每一个对象

bool badValue(int );
  • 1
//对于序列容器,(vector,string,deque,list)把每个remove调用换成remove_if就行了,这是最好的方法。
c.erase(remove_if(c.begin,c.end,badValue),c.end);

//当c时list时
c.remove_if(badValue);

//对于关联容器有两种方法,一种是易于编码,一种是效率高。

//1.简单效率低
//利用remove_copy_if()把我们需要的值复制到一个新的容器中,然后把原来容器的内容和新容器的内容进行交换。
AssocContainer<int> c;
AssocContainer<int> goodValues;         //标准关联容器。
remove_copy_if(c.begin(),c.end(),insert(goodValues,goodValues.end()),badValue);
c.swap(goodValues);                     //交换两容器中的内容。

//2效率高。
AssocContainer<int> c;                  //标准关联容器。
for(AssocContainer<int>::iterator i=c.begin();i!=c.end();)
{
    if(badValue(*i))
        c.eraser(i++);
    else
        i++;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

vector迭代器返回的是 下一个位置的迭代器。 
map 和 set 返回的是 void 。 
3.删除使得下列判别式返回true的每一个对象 
bool badValue(int )以及每次元素删除时,都向log文件中写入一条信息。

//对于序列容器,不能使用erase-remove,因为没办法使用这两个向日志文件中写入信息。
//并且不能使刚才为关联容器设置的循环,因为对于这类容器erase不仅会使指向被删除元素的迭代器无效。
//也会使删除元素后的所有迭代器都无效。
//序列容器erase返回的是下一个位置的迭代器
//关联容器erase返回void
for(SeqContainer<int>::iterator i=c.begin();i!=c.end();)
{
    if(badValue(*i))
    {
        logFile<<"Erasing"<<*i<<endl;
        i=c.eraser(i);
    }
    else
        i++;
}


//关联容器只需做出一点修改
ofstream logFile;
AssocContainer<int> c;                 
for(AssocContainer<int>::iterator i=c.begin();i!=c.end();)
{
    if(badValue(*i))
    {
        logFile<<"Erasing"<<*i<<endl;
         c.eraser(i++);
    }
    else
        i++;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值