C++ vector 刪除符合條件的元素


C++ vector中實際刪除元素使用的是容器vecrot中std::vector::erase()方法。

C++ 中std::remove()並不刪除元素,因為容器的size()沒有變化,只是元素的替換。

1.std::vector::erase()

  函數原型:iterator erase (iterator position);  //刪除指定元素

       iterator erase (iterator first, iterator last);  //刪除指定范圍內的元素

  返回值:指向刪除元素(或范圍)的下一個元素。(An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.)

2.代碼實例

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 using namespace std;
 5 
 6 int out(vector<int> &iVec)
 7 {
 8     for(int i=0;i<iVec.size();i++)
 9         cout<<iVec[i]<<ends;
10     cout<<endl;
11     return 0;
12 }
13 
14 int main()
15 {
16     vector<int> iVec;
17     vector<int>::iterator it;
18     int i;
19     for( i=0;i<10;i++)
20         iVec.push_back(i);
21 
22     cout<<"The Num(old):";out(iVec);
23     for(it=iVec.begin();it!=iVec.end();)
24     {
25         if(*it % 3 ==0)
26             it=iVec.erase(it);    //刪除元素,返回值指向已刪除元素的下一個位置    
27         else
28             ++it;    //指向下一個位置
29     }
30     cout<<"The Num(new):";out(iVec);
31     return 0;
32 }

 執行輸出:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM