C + + Vector Delete eligible element sample share _c language

Source: Internet
Author: User
Tags function prototype

The actual deletion element in the C + + vector uses the container Vecrot std::vector::erase () method.

Std::remove () in C + + does not delete the element because the size () of the container does not change, just the substitution of the element.

1.std::vector::erase ()

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

Iterator Erase (iterator, iterator last);//delete elements within the specified range

Return value: Point to the next element of the delete element (or range). (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" operation erased the last element in the sequence.)

2. code example

Copy Code code as follows:

#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
Else
++it; Point to Next location
}
cout<< "The Num (new):"; Out (Ivec);
return 0;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.