栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ vector删除符合条件的元素示例分享

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.代码实例

复制代码 代码如下:
#include
#include
#include
using namespace std;

int out(vector &iVec)
{
    for(int i=0;i        cout<    cout<    return 0;
}

int main()
{
    vector iVec;
    vector::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;
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/65849.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号