如何选择STL容器中对象的删除方法

备注:唯一从容器中除去一个元素的方法是在那个容器上调用一个成员函数。

 

  以下介绍删除不同类型的容器中满足某种条件的值的方法,某种条件指的是

bool badValue(int value)返回true的情况。

1、序列容器

for(SeqContainer<int>::iterator i = c.begin();
    i != c.end();
    /*nothing*/)
{
    if(badValue(*i))
    {
        //something to do
        i = c.erase(i);
    }
    else
        ++i;
}

这种情况下,一旦删除完成,erase的返回值它就是指向紧接在被删元素之后的元素的有效迭代器。

 

2、关联容器

for(AssocContainer<int>::iterator i = c.begin(); 
    i !=c.end();
    /*nothing*/)
{
    if (badValue(*i))
    {
        //something to do
        c.erase(i++); // 删除元素
    }
    else 
        ++i;
}

 

这种情况下,在erase开始执行前i已经自增了。

 

3、高效的方法(STL算法或容器自带算法)

3.1 序列容器,如SeqContainer<int> c:

  对于vector、deque或string,删除特定值,使用erase-remove:

c.erase(remove(c.begin(), c.end(), 1234), c.end());

  对于vector、deque或string,删除满足条件的值,使用erase-remove_if:

c.erase(remove_if(c.begin(), c.end(), badValue), c.end());

  对于List,删除特定值,使用自带的remove:

c.remove(1234);

  对于List,删除满足条件的值,使用自带的remove_if:

c.remove_if(badValue);

3.2 关联容器,如AssocContainer<int> c:

  标准关联容器(即set、multiset、map或multimap)并没有叫做remove的成员函数。

删除特定值方法,c.erase(1234);删除满足条件的值,见(2、关联容器)。

本文出自 商显技术博客,转载时请注明出处及相应链接。

本文永久链接: http://www.uchar.cn/?p=287

posted on 2014-07-10 23:41  richardor  阅读(376)  评论(0编辑  收藏  举报

导航