C++ vector刪除符合條件的元素示例分享
C++ vector中實際刪除元素使用的是容器vecrot std::vector::erase()方法。
C++ 中std::remove()并不刪除元素,因為容器的size()沒有變化,只是元素的替換。
1.std::vector::erase()
函數(shù)原型:iterator erase (iterator position);//刪除指定元素
iterator erase (iterator first, iterator last);//刪除指定范圍內(nèi)的元素
返回值:指向刪除元素(或范圍)的下一個元素。(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.代碼實例
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int out(vector<int> &iVec)
{
for(int i=0;i<iVec.size();i++)
cout<<iVec[i]<<ends;
cout<<endl;
return 0;
}
int main()
{
vector<int> iVec;
vector<int>::iterator it;
int i;
for( i=0;i<10;i++)
iVec.push_back(i);
cout<<"The Num(old):";out(iVec);
for(it=iVec.begin();it!=iVec.end();)
{
if(*it % 3 ==0)
it=iVec.erase(it); //刪除元素,返回值指向已刪除元素的下一個位置
else
++it; //指向下一個位置
}
cout<<"The Num(new):";out(iVec);
return 0;
}

相關(guān)文章
VC List Control控件如何刪除選中的記錄實例詳解
這篇文章主要介紹了VC List Control控件如何刪除選中的記錄實例詳解的相關(guān)資料,需要的朋友可以參考下2017-06-06一篇文章帶你了解C++ static的作用,全局變量和局部變量的區(qū)別
這篇文章介紹了C++ static的作用,全局變量和局部變量的區(qū)別,需要的朋友可以過來參考下,希望能夠給你帶來幫助2021-09-09C++通過循環(huán)實現(xiàn)猜數(shù)字小游戲
這篇文章主要為大家詳細介紹了C++通過循環(huán)實現(xiàn)猜數(shù)字小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-09-09