編程時我們經常遇到要“刪除與某值相等的元素”的問題。
假設序列3 1 3 2 3 3 3 4 3 5 3 6,要把序列中的3刪除,我們可以使用如下代碼:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
freopen("test.in","r",stdin);
vector<int> coll;
int i;
while(cin>>i){
coll.push_back(i);
}
coll.erase(remove(coll.begin(),coll.end(),3),coll.end());
copy(coll.begin(),coll.end(),ostream_iterator<int>(cout," "));
return 0;
}
在STL中erase(beg,end)移除[beg,end]區間內的所有元素,返回下一元素的位置。
remove(beg,end,val)移除[beg,end]區間內所有值爲val的元素,返回一個新的end位置。
爲什麼要在erase中嵌套remove呢?
自己動手試一試,直接用remove會發現輸出結果是1 2 4 5 6 3 3 4 3 5 3 6,前面的5個數字是我們想要的結果,但後面的7個數字不是我們想要的。前面說了,remove會返回一個新的end位置,這個位置剛好指向7個數字裏的第一個,所以要在erase中嵌套remove。
如果只想把第一個3給刪除要怎麼辦呢?
可以使用如下代碼:
...
vector<int>::iterator pos;
pos=find(coll.begin(),coll.end(),3);
if (pos!=coll.end()){
coll.erase(pos);
}
...
這段代碼見名思意了,值得一提的是find函數如果沒有查找到相應的值會返回一個end()的位置。
留幾個小問題,僅供茶餘飯後思考娛樂:
1.刪除前3個3。
2.保留最後一個3,刪除其餘的3。