Vector is a very useful container in C + +, and here's a summary of the container. 1 Basic Operations
(1) header file #include<vector>.
(2) Declaration and initialization of vector variables
Vector<int> A; declares an int-type vector a
vector<int> a (a); Declares a vector with an initial size of 10
vector<int> A (1); Declares a vector
vector<int> B (a) with an initial size of 10 and an initial value of 1; Declares and uses vector A to initialize vector b
vector<int> B (A.begin (), A.begin () +3); The initial value of vector b from the No. 0 to 2nd (total 3) in a vector
In addition, you can initialize vectors directly by using arrays:
int n[] = {1, 2, 3, 4, 5};
Vector<int> A (n, n+5); The first 5 elements of the array n are used as the initial value of vector a
(vector<int> a (&n[1], &n[4]); To use an element within the n[1]-n[4] range as the initial value of a vector a
(3) Tail Insert number: Vec.push_back (a);
(4) Use subscript to access elements,cout<<vec[0]<<endl; remember that subscripts start at 0.
(5) Accessing elements using iterators.
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.begin () +j); Delete interval [i,j-1]; interval starting from 0
(8) Vector size: vec.size ();
(9) Empty: Vec.clear (); 2
Vector elements can not only make int,double,string, but also structural body, but note: The structure is defined as global, otherwise there will be errors. The following is a short program code:
#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 comparison functions within the structure, sorted by Id,length,width ascending order.
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) Use reverse to flip the element: Requires a header file #include<algorithm>
Reverse (Vec.begin (), Vec.end ()); Flip the element (in vector, if two iterators are required in a function, the latter does not normally contain.)
(2) Use sort order: Need header file #include<algorithm>,
Sort (Vec.begin (), Vec.end ());(default is in ascending order, that is, from small to large.
You can compare the sort comparison functions by overriding them in descending order, as follows:
To define a sort comparison function:
BOOL Comp (const int &A,CONST int &b)
{
Return a>b;
}
When called: Sort (Vec.begin (), Vec.end (), Comp), sorted in descending order.