This article mainly introduces the vector is a very useful container in C + +, the following is a summary of the container
1 Basic Operation (1) header file #include<vector>. (2) Create vector object,vector<int> VEC; (3) Tail Insert number: Vec.push_back (a); (4) using subscript to access elements,cout<<vec[0]<<endl; remember that subscripts start at 0. (5) Accessing elements using iterators. Code is as follows: Vector<int>::iterator it; For (It=vec.begin (); It!=vec.end (); it++) cout<<*it<<endl; (6) Insert element: vec.insert (Vec.begin () +i,a); Insert a in front of the i+1 element; (7) Delete element: vec.erase (Vec.begin () +2); Delete 3rd element Vec.erase (Vec.begin () +i,vec.end () +j); Delete interval [I, J-1]; Range starting from 0 (8) vector size: vec.size (); (9) Empty: Vec.clear (); 2 Vector elements can not only make int,double,string, but also structure, but note: The structure is defined as global, otherwise there will be an error. The following is a short program code: Code as follows: #include <stdio.h> #include <algorithm> #include <vector> # Include<iostream> using namespace std; typedef struct RECT { int id; int length; int width; //for vector element is structure Body, you can define the comparison function within the structure, sorted by Id,length,width ascending order below. BOOL operator< (const rect &a) const { (id!=a.id) &NBSP ; return id<a.id; else { if (Length!=a.leng TH) return length<a.length; else return WIDTH<A.W Idth; } }rect; int main () { vector<rect> VEC Rect Rect; rect.id=1; rect.length=2; rect.width=3; Vec.push_back (rect); Vector<rect>::iterator it=vec.begin (); cout<< (*it) .id<< ' << (*it) .length<< ' << (*it) .width<<endl; return 0; } 3 algorithm (1) Flip elements using reverse: Header file #include<algorithm> reverse (Vec.begin (), Vec.end ()); Flip the element (in vector, If two iterators are required in a function, the generally does not include the latter.) (2) Using sort sorting: Requires header file #include<algorithm>, sort (vec.begin (), Vec.end ());(default is in ascending order, that is, from small to large. can be compared by overriding the sort comparison function in descending order: Defining the Sort comparison function: Copy code code as follows: BOOL Comp (const int &a,const int &b) {&NB Sp Return a>b; When called: Sort (Vec.begin (), Vec.end (), Comp), sorted in descending order.