国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++ vector刪除符合條件的元素示例分享

2020-01-26 15:36:06
字體:
來源:轉載
供稿:網友

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.代碼實例

復制代碼 代碼如下:

#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;
}



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 海原县| 湟源县| 乌兰浩特市| 宁化县| 大埔县| 浠水县| 定远县| 衡南县| 新和县| 西贡区| 罗平县| 崇左市| 南宫市| 长治县| 平山县| 望都县| 乡城县| 鱼台县| 当涂县| 旅游| 浪卡子县| 麻城市| 南汇区| 鸡西市| 英吉沙县| 竹溪县| 江孜县| 库尔勒市| 襄垣县| 梁河县| 简阳市| 济源市| 安远县| 龙里县| 洛川县| 砀山县| 抚州市| 慈利县| 屏山县| 灵川县| 洞口县|