如何選擇STL容器中對象的刪除方法

來源:互聯網
上載者:User

標籤:style   http   color   使用   strong   os   

備忘:唯一從容器中除去一個元素的方法是在那個容器上調用一個成員函數。

 

  以下介紹刪除不同類型的容器中滿足某種條件的值的方法,某種條件指的是

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.