C++ vector刪除合格元素樣本分享_C 語言

來源:互聯網
上載者:User

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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.