1、對于連續內存的容器(vector,dequeu,string),最好的方法是用erase - remove
c.erase(remove(c.begin(),c.end(),1963),c.end());
/* remove(first,end,value) :
The remove algorithm removes all elements that match value from the range (First, Last). It returns an iterator equal to Last - n, where n = number of elements removed. That is ,if c is {3,2,1963,12,1963,16}, after remove , c is {3,2,12,16,1963,1963}.*/
2、對于list,c.remove(1963);
3、對于關聯容器(map,set) 可以用c.erase(1963); 而且開銷是對數時間的。而前兩條中的開銷是線性的。
3、如果是要刪除滿足某一條件的值,對于連續內存的容器(vector,dequeu,string),用erase - remove_if。對于list,用remove_if
c.erase(remove_if(c.begin(),c.end(),yourcondition),c.end()); /*刪除使youcondition為true的值*/
4、對于關聯容器,必須遍歷整個容器中的元素了。
下面是重點:
下面的程序是不對的
AssocContainer<int>c;

for(AssoContainer<int>::iterator i=c.begin();i!=c.end();i++)
if(youcondition(*i)) c.erase(i);
因為當把i刪除后,i就變成了無效的值。這樣,后面的i++就無效了。
解決這個問題的最簡單的方法是:
5、第4條所述的方法,只對關聯容器起作用。對于vector,string,dequeu,上面的方法會出錯。因為這類容器,當刪除一個元素后,不僅指向被刪除的元素的迭代器無效,也會使被刪除元素之后的所有的迭代器失效。
這時,我們要用erase的返回值。erase返回被刪除元素的下一個元素的有效的迭代器。
因此可以這樣
SeqContainer<int>c;

for(SeqContainer<int>::iterator i=c.begin();i!=c.end();)
{
if(youcondition(*i))
{
dosomething(*it);
i=c.erase(i);
}
else i++;
}
還要注意,對于關聯容器,erase返回void.
總結:
● 去除一個容器中有特定值的所有對象:
如果容器是vector、string或deque,使用erase-remove慣用法。
如果容器是list,使用list::remove。
如果容器是標準關聯容器,使用它的erase成員函數。
● 去除一個容器中滿足一個特定判定式的所有對象:
如果容器是vector、string或deque,使用erase-remove_if慣用法。
如果容器是list,使用list::remove_if。
如果容器是標準關聯容器,使用remove_copy_if和swap,或寫一個循環來遍歷容器元素,當你把迭代器傳給erase時記得后置遞增它。
● 在循環內做某些事情(除了刪除對象之外):
如果容器是標準序列容器,寫一個循環來遍歷容器元素,每當調用erase時記得都用它的返回值更新你的迭代器。
如果容器是標準關聯容器,寫一個循環來遍歷容器元素,當你把迭代器傳給erase時記得后置遞增它。