Reproduced in: http://blog.csdn.net/longshengguoji/article/details/8507394
The vector class, known as the vectors class, implements a dynamic array, an array of objects used to change the number of elements. Like arrays, the vector class also represents the position of the element with a subscript starting from 0, but the array is different when the vector object is created, and the number of elements of the arrays automatically changes as the number of vector objects increases and shrinks.
The functions commonly used by the vector class are as follows:
1. Constructors
- Vector (): Create an empty vector
- Vector (int nSize): Creates a vector with the number of elements nSize
- Vector (int nsize,const t& t): Creates a vector with an element number of nSize and a value of T
- Vector (const vector&): copy constructor
- Vector (begin,end): Copies the elements of another array within the [Begin,end] range into the vector
2. Add function
- void push_back (const t& x): Adds an element x to the tail of a vector
- Iterator Insert (iterator it,const t& x): Adds an element x before the iterator points to the element in a vector
- Iterator Insert (iterator it,int n,const t& x): Adds n the same element x before the iterator points to the element in a vector
- Iterator Insert (iterator It,const_iterator first,const_iterator last): Data between an iterator in a vector and a [first,last] that inserts another vector of the same type before it points to the element
3. Delete a function
- Iterator Erase (iterator it): Removing an iterator to an element in a vector
- Iterator Erase (iterator first,iterator last): delete element in vector [First,last]
- void Pop_back (): Delete the last element in a vector
- void Clear (): empties all elements in the vector
4. Traversing functions
- Reference at (int pos): Returns a reference to the POS location element
- Reference Front (): Returns a reference to the first element
- Reference back (): Returns a reference to the tail element
- Iterator begin (): Returns the vector head pointer, pointing to the first element
- Iterator End (): Returns the vector tail pointer, pointing to the next position of the last element of the vector
- Reverse_iterator rbegin (): Reverse iterator, pointing to the last element
- Reverse_iterator rend (): Reverse iterator, pointing to the position before the first element
5. Judging function
- BOOL Empty () Const: Determines whether the vector is empty, and if it is empty, no element in the vector
6. Size function
- int size () const: Returns the number of elements in a vector
- int capacity () const: Returns the maximum element value that the current vector Zhang can hold
- int max_size () const: Returns the maximum allowable vector element number value
7. Other functions
- void Swap (vector&): Exchange data for two vectors of the same type
- void assign (int n,const t& x): Sets the value of the nth element in a vector to X
- void Assign (Const_iterator first,const_iterator last): The element in the vector [First,last] is set to the current vector element
Vector member functions
Function |
Expression |
C.assign (Beg,end) C.assign (N,elem) |
Assigns the data in the [beg; end] Interval to C. Assigns a copy of n elem to C. |
c.at (IDX) |
Returns the index IDX refers to the data, if the IDX is out of bounds, throws Out_of_range. |
C.back () |
Returns the last data without checking to see if the data exists. |
C.begin () |
Returns a data that is valued by the iterator. |
C.capacity () |
Returns the number of data in the container. |
C.clear () |
Removes all data from the container. |
C.empty () |
Determines whether the container is empty. |
C.end () |
Points to the last data address in the iterator. |
C.erase (POS) C.erase (Beg,end) |
Deletes data from the POS location and returns the location of the next data. Delete the data from the [Beg,end] interval and return to the location of the next data. |
C.front () |
Returns a data back to the ground. |
Get_allocator |
Use the constructor to return a copy. |
C.insert (Pos,elem) C.insert (Pos,n,elem) C.insert (Pos,beg,end) |
Inserts a elem copy at the POS location and returns the new data location. Inserts n elem data at the POS location. no return value. Inserts the data in the [Beg,end] interval at the POS location. no return value. |
C.max_size () |
Returns the maximum number of data in a container. |
C.pop_back () |
Delete the last data. |
C.push_back (Elem) |
Add a data to the trailer. |
C.rbegin () |
Returns the first data for a reverse queue. |
C.rend () |
Returns the next position of the last data in a reverse queue. |
C.resize (num) |
Re-specify the length of the queue. |
C.reserve () |
Keep the appropriate capacity. |
C.size () |
Returns the number of actual data in the container. |
C1.swap (C2) Swap (C1,C2) |
Swaps the C1 and C2 elements. Above operation. |
Vector<elem> C Vector <Elem> C1 (C2) Vector <Elem> C (n) Vector <Elem> C (n, Elem) Vector <Elem> C (beg,end) c.~ Vector <Elem> () |
Create an empty vector. Copy a vector. Create a vector that contains n data, and the data is constructed by default. Create a vector containing n elem copies. Create a vector with an interval of [beg;end]. Destroys all data and frees up memory. |
Vector Operation
Function |
Describe |
Operator[] |
Returns a reference to the specified position in the container. |
Example: 1. Initialization example
#include "stdafx.h" #include <iostream> #include <vector>using namespace Std;class a{//empty class};int _tmain (int ARGC, _tchar* argv[]) {//int type vectorvector<int> vecint;//float type vectorvector<float> vecfloat;//custom type, Save the Vectorvector<a> veca;//custom type of Class A, save the pointer to Class A vectorvector<a*> Vecpointa;return 0;}
Vectorsample.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <vector>using namespace Std;class a{//empty class};int _tmain (int ARGC, _tchar* argv[]) {//int vector, containing 3 elements vector<int> Vecinta (3);//int vector, containing 3 elements and each element is 9vector<int > Vecintb (3,9);//Copy Vecintb to vecintcvector<int> VECINTC (VECINTB); int iarray[]={2,4,6};//Create Vecintdvector <int> Vecintd (iarray,iarray+3);//print Vectora, where the code in the following comment can be used to output the data/*for in the vector (int i=0;i<vecinta.size (); i+ +) {cout<<vecinta[i]<< "";} */cout<< "Vecinta:" <<endl;for (Vector<int>::iterator it = Vecinta.begin (); It!=vecIntA.end (); it++) {cout<<*it<< "";} cout<<endl;//print vecintbcout<< "VECINTB:" <<endl;for (vector<int>::iterator it = VecIntB.begin (); It!=vecintb.end (); it++) {cout<<*it<< "";} cout<<endl;//print vecintccout<< "VECINTB:" <<endl;for (vector<int>::iterator it = VecIntC.begin (); It!=vecintc.end (); it++) {Cout<<*it<< "";} cout<<endl;//print vecintdcout<< "Vecintd:" <<endl;for (vector<int>::iterator it = VecIntD.begin (); It!=vecintd.end (); it++) {cout<<*it<< "";} Cout<<endl;return 0;}
The running results of the program are as follows:
The code above uses 4 ways to build a vector and initialize it.
2. Add and get element examples:
Vectorsample.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <vector>using namespace std;int _tmain (int argc, _tchar* Argv[]) {//int vector, containing 3 elements vector<int> vecinta;//insert 1 2 3vecinta.push_back (1); Vecinta.push_back (2); Vecinta.push_back (3); int nSize = Vecinta.size ();cout<< "Vecinta:" <<endl;//print Vectora, method one: for (int i=0;i <nsize;i++) {cout<<vecinta[i]<< " ";} cout<<endl;//Print Vectora, method two: for (int i=0;i<nsize;i++) {cout<<vecinta.at (i) << " ";} cout<<endl;//print Vectora, method three: for (vector<int>::iterator it = Vecinta.begin (); It!=vecinta.end (); it++) { cout<<*it<< " ";} Cout<<endl;return 0;}
The above code for a shape vector class operation, first define a shape element vector class, and then insert 3 values, and 3 different methods output, the program run the result is as follows:
Vectorsample.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <vector>using namespace Std;class a{public:int n;public: A (int n) {this->n = n;}}; int _tmain (int argc, _tchar* argv[]) {//int-type vector, containing 3 elements vector<a> Vecclassa; A A1 (1); A A2 (2); A A3 (3);//INSERT 1 2 3vecclassa.push_back (A1); vecclassa.push_back (A2); Vecclassa.push_back (A3); int nSize = Vecclassa.size ( );cout<< "Vecclassa:" <<endl;//print Vecclassa, method one: for (int i=0;i<nsize;i++) {COUT<<VECCLASSA[I].N << " ";} cout<<endl;//Print Vecclassa, method two: for (int i=0;i<nsize;i++) {cout<<vecclassa.at (i) .n<< " ";} cout<<endl;//print Vecclassa, method three: for (vector<a>::iterator it = Vecclassa.begin (); It!=vecclassa.end (); it++) {cout<< (*it) .n<< " ";} Cout<<endl;return 0;}
The code above is done by defining the elements as vectors of the class, by inserting 3 initialized classes, and outputting through 3 methods, the result is as follows:
Vectorsample.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <vector>using namespace Std;class a{public:int n;public: A (int n) {this->n = n;}}; int _tmain (int argc, _tchar* argv[]) {//int-type vector, containing 3 elements vector<a*> Vecclassa; A *a1 = Newa (1); A *a2 = new A (2); A *a3 = new A (3);//INSERT 1 2 3vecclassa.push_back (A1); vecclassa.push_back (A2); Vecclassa.push_back (A3); int nSize = Vecclassa.size ();cout<< "Vecclassa:" <<endl;//print Vecclassa, method one: for (int i=0;i<nsize;i++) {cout< <vecClassA[i]->n<< "\ T";} cout<<endl;//Print Vecclassa, method two: for (int i=0;i<nsize;i++) {cout<<vecclassa.at (i)->n<< "\ T";} cout<<endl;//print Vecclassa, method three: for (vector<a*>::iterator it = Vecclassa.begin (); It!=vecclassa.end (); it++ ) {cout<< (**it) .n<< "\ T";} Cout<<endl;delete A1; Delete a2;delete A3;return 0;}
The above code runs the result by defining the element as a vector of class pointers, by inserting 3 initialized class pointers, and outputting the class to which the pointer points through 3 methods:
3. Modify element Examples There are three ways to modify elements: 1. Modify by array, 2. Modify by reference, 3. Using iterators to modify
Vectorsample.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <vector>using namespace std;int _tmain (int argc, _tchar* Argv[]) {//int vector, containing 3 elements vector<int> vecinta;//insert 1 2 3vecinta.push_back (1); Vecinta.push_back (2); Vecinta.push_back (3); int nSize = Vecinta.size ();//Modify by reference vectorcout<< "modified by array, the second element is 8:" <<endl;vecinta[1 ]=8;cout<< "Vecinta:" <<endl;//print vectorafor (vector<int>::iterator it = VecIntA.begin (); it!= Vecinta.end (); it++) {cout<<*it<< "";} cout<<endl;//Modify vectorcout<< by reference "modified by reference, the second element is:" <<endl;int &m = vecinta.at (1); m=18;cout << "Vecinta:" <<endl;//print vectorafor (vector<int>::iterator it = Vecinta.begin (); It!=vecinta.end (); it++) {cout<<*it<< "";} cout<<endl;//modified by Iterators vectorcout<< "modified by iterators, the second element is" <<endl;vector<int>::iterator ITR = Vecinta.begin () +1;*itr = 28;cout<< "Vecinta:" <<endl;//print vectorafor (vector<int>::iteraTor it = Vecinta.begin (); It!=vecinta.end (); it++) {cout<<*it<< "";} Cout<<endl;return 0;}
The result of the program operation is as follows: 4. Delete Vector sample Delete vector mainly through erase and pop_back, the sample code is as follows
Vectorsample.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <vector>using namespace std;int _tmain (int argc, _tchar* Argv[]) {//int vector, containing 3 elements vector<int> vecinta;//loop inserted 1 to 10for (int i=1;i<=10;i++) {vecinta.push_back (i);} Vecinta.erase (Vecinta.begin () +4);cout<< "Delete the 5th element after the vector vecinta:" <<endl;//print vectorafor (vector<int >::iterator it = Vecinta.begin (); It!=vecinta.end (); it++) {cout<<*it<< "\ T";} cout<<endl;//Delete 第2-5个 element vecinta.erase (Vecinta.begin () +1,vecinta.begin () +5);cout<< "Delete 第2-5个 element after VecIntA : "<<endl;//print vectorafor (vector<int>::iterator it = Vecinta.begin (); It!=vecinta.end (); it++) {cout< <*it<< "\ T";} cout<<endl;//Delete the last element Vecinta.pop_back ();cout<< "Delete the last element after the Vecinta:" <<endl;//print vectorafor ( Vector<int>::iterator it = Vecinta.begin (); It!=vecinta.end (); it++) {cout<<*it<< "\ T";} Cout<<endl;return 0;}
The result of the program operation is as follows: 3. Further understanding of vectors, as shown in: when executing code vector<int> V (2,5), creates 2 elements of shaping space in memory, The value is 5. When an element is added, the original space is programmed by 2 to 4 shaping element space, and the element 1 is placed in the 3rd shaping space, and the 4th space as a reserved space. When the element 2 o'clock is added, the value 2 is placed directly into the 4th space. When the element 3 o'clock is added, since there is no reserved space in the original vector, the memory space is changed from 4 to 8 shaping space, and the value is placed into the 5th memory space. In short, when you expand the new element, if you exceed the current capacity, the capacity will automatically expand twice times, if twice times the capacity is still insufficient, then continue to expand twice times. This figure is directly on the original space based on the new space, in fact, more complex, including reconfiguration, element movement, the process of releasing the original space. Therefore, for vector containers, when adding new elements, it is possible to complete (directly existing in the reserved space), may be slightly slower (expansion and then put new elements), to modify the value of the element is faster, for the deletion of elements, the weak deletion of the tail element is faster, non-trailer element is slightly slower, because it involves the deletion of the element 4. Comprehensive examples
Vectorsample.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream> #include <vector> #include <string>using namespace std; Class student{public:string m_strno;string m_strname;string m_strsex;string m_strdate;public:student (String StrNO, String strname,string strsex,string strdate) {M_strno = Strno;m_strname = Strname;m_strsex = Strsex;m_strdate = strDate;} void Display () {cout<<m_strno<< "\ t";cout<<m_strname<< "\ T";cout<<m_strsex<< "\ T ";cout<<m_strdate<<" \ n ";}}; Class studcollect{vector<student> m_vstud;public:void Add (Student &s) {m_vstud.push_back (s);} student* Find (String strno) {bool bfind = False;int i;for (i = 0;i < M_vstud.size (); i++) {student& s = m_vstud.at (i); I F (S.m_strno = = Strno) {bfind = True;break;}} Student *s = null;if (bfind) s = &m_vstud.at (i); return s;}}; int _tmain (int argc, _tchar* argv[]) {Student S1 ("1001", "Zhangsan", "Boy", "1988-10-10"); Student S2 ("1002", "Lisi", "Boy", "1988-8-25"); Student S3 ("1003", "Wangwu", "Boy", "1989-2-14"); Studcollect S;s.add (S1); S.add (S2); S.add (S3); Student *ps = S.find ("1002"), if (PS) Ps->display (); return 0;}
The code runs the following example:
STL II: A detailed description of vector container usage