In C + +, vector is a very useful container, and here is a summary of the container.
1 Basic operations
(1) header file #include<vector>.
(2) Create vector object,vector<int> VEC;
(3) Insert number at tail: vec.push_back (a);
(4) Use subscript to access the element,cout<<vec[0]<<endl; remember that the subscript is starting from 0.
(5) Use iterators to access elements.
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 first 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]; interval starting from 0
(8) Vector size: vec.size ();
(9) Empty: Vec.clear ();
2
The elements of the
vector can not only make int,double,string, but also structs, but be aware that the struct is defined as global, or else an error occurs. Here is a short code for the program:
#include <stdio.h> #include <algorithm> #include <vector> #include <iostream>using namespace std;typedef struct rect{ int id; int length; int width; For vector elements that are structural, you can define a comparison function within the structure, sorted in ascending order of Id,length,width. bool operator< (Const rect &a) const { if (id!=a.id) return id<a.id; else { if (length!=a.length) return length<a.length; else return width<a.width; } }}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 the element with reverse: Requires a header file #include<algorithm>
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) Sorting by using sort: Requires header file #include<algorithm>
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.
Substitution of arrays--template vector, use of array