in the C + + in which Vector is a very useful container, here is a summary of the container.
1 Basic Operations
(1) header File #include <vector>.
(2) Create Vector objects, vector<int> Vec;
(3) trailing insert Number: Vec.push_back (a);
(4) use subscript to access elements, cout<<vec[0]<<endl; Remember that the subscript is from 0 the beginning.
(5) using 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); in section i+1 elements in front of the insert A;
(7) To Delete an element: ??? Vec.erase (Vec.begin () +2); Delete section 3 an element
vec.erase (Vec.begin () +i,vec.end () +j); Delete Interval [i,j-1]; interval from 0 Start
(8) Vector size : Vec.size ();
(9) Clear : Vec.clear ();
2
Vector element can not only make int,double,string, It can also be a struct, but be aware that the struct is defined as global, otherwise an error occurs. Here is a short program code:
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <iostream>
Usingnamespace std;
?
typedef struct rect
{
int ID;
int length;
Span style= "color:blue; Font-family:courier new ">int width;
// for a vector element is a struct, you can define a comparison function within a struct, followed by id,length,width ascending sort.
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;
?
return0;
?
}
? 3? algorithm
(1) flip element with reverse : Requires header file #include <algorithm>
Reverse (Vec.begin (), Vec.end ()); Flip an element ( in vector , if two iterators are required in a function,
usually the last one does not contain .)
(2) Use Sort sort: Requires header file #include <algorithm> ,
sort (Vec.begin (), Vec.end ());( By default it is sorted 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;
}
when called : Sort (Vec.begin (), Vec.end (), Comp) , so it's sorted in descending order.
?
Original: http://www.cnblogs.com/wang7/archive/2012/04/27/2474138.html
?
C + + vector usage (RPM)