Vector container in C + +

Source: Internet
Author: User

In C + +, vector is a very useful container, and here is a summary of the container.

1. Basic operation

(1) header file #include <vector>.

(2) Create vector object vector<int> VEC;

(3) Insertion of the trailing digit vec.push_back (a);

(4) Use subscript to access element cout<<vec[0]<<endl; //Remember that the subscript is starting from 0.

(5) using iterators to access elements

Vector<int>::iterator it;for (It=vec.begin (); It!=vec.end (); it++)
{
cout<<*it<<endl;
}

(6) inserting element Vec.insert (Vec.begin () +i,a); //Insert a in front of the first I+1 element

(7) Delete element Vec.erase (Vec.begin () +2); //Delete element 3rd

Vec.erase (Vec.begin () +i,vec.end () +j); //delete interval [i,j-1]; interval starting from 0

(8) Vector size vec.size ();

(9) empty vec.clear ();

Note: Vector elements can not only make the int,double,string, but also the structure, but note: The structure should be defined as global, otherwise it will be wrong.

2. Algorithm

Header file Required #include<algorithm>

(1) Using reverse to flip elements

Reverse (Vec.begin (), Vec.end ()); Flips the element (in a vector, if two iterators are required in a function,

Usually the latter is not included.)

(2) Sort by using sort

Sort (Vec.begin (), Vec.end ());(by default in ascending order, that is, from small to large).

You can compare functions in descending order by overriding the sort comparison, as follows:

To define a sort comparison function:

BOOL Comp (const int &A,CONST int &b)
{
Return a>b;
}
Called When: Sort (Vec.begin (), Vec.end (),Comp), so that it is sorted in descending order.

Vector container in C + +

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.