C++ vector removes qualified elements for example sharing

  • 2020-04-02 02:12:41
  • OfStack

The actual deletion of elements in C++ vector USES the container vecrot STD ::vector::erase() method.

STD ::remove() in C++ does not remove the element, because the size of the container () does not change, just replaces the element.

1. The STD: : vector: : erase ()

Function prototype: iterator erase (iterator position); // deletes the specified element

Iterator first, iterator last; // deletes an element in the specified range

Return value: points to the next element of the deleted element (or scope). (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. Code instances


#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);    //Deletes an element and the return value points to the next location of the deleted element & PI; & have spent & have spent
        else
            ++it;    //Point to the next position
    }
    cout<<"The Num(new):";out(iVec);
    return 0;
}


< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201402/20140227101620.jpg? 2014127101654 ">


Related articles: