• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

c++ 搞代码 4年前 (2022-01-06) 78次浏览 已收录 0个评论

这篇文章主要介绍了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<iVec.size来源[email protected]搞@^&代*@码网();i++)
        cout<<iVec[i]<<ends;
    cout<<endl;
    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;
}

以上就是C++ vector删除符合条件的元素示例分享的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++ vector删除符合条件的元素示例分享

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址