What is Vector?
Vector is translated into vector, which is a variable-length array in some ways. It can automatically expand the capacity of the array as needed. Besides, it is a template class in STL.
There are also some internal methods.
Use of Vector
1. Add header files
# include <iostream> # include <vector> using namespace std;
2. Defining vector Objects
vector<int> name; vector<double> name;//Double precision type vector <float> name;//Floating point type vector <char> name;//Character
vector<vector<int>> name;//Similar to two-dimensional arrays
3. Access vector s internal elements
1) Access elements through Subscripts
//Access via Subscripts vector<typename> v; cout<<v[0]<<endl;
2) Access through iterators
Iterators can be understood as pointer-like things, defining their methods.
vector<typename> ::iterator it; vector<int>::iterator it; vector<float>::iterator it;
Give an example
# include <iostream> # include <vector> using namespace std; int main(void) { vector<int> vi; for(int i=1;i<=5;i++) { vi.push_back(i); } //vi.begin()Is to take vi The first address, it Point to the address vector<int>::iterator it=vi.begin(); for(int i=0;i<5;i++) { cout<<*(it+i)<<endl; } }
Result
Note that the begin() function returns the first address of the vector array, while end() does not return the tail address, but the address of the next element of the tail element. In addition, the iterator implements two self-incremental operations, it++ and ++ it.
So the second method of iterator traversal is used.
# include <iostream> # include <vector> using namespace std; int main(void) { vector<int> vi; for(int i=0;i<5;i++) { vi.push_back(i); }
//It < VI. end () is not supported for(vector<int>::iterator it=vi.begin();it!=vi.end();it++) { cout<<*it<<' '<<endl; } return 0; }
4. Use of Common Functions
1)push_back()
Function: Add an element after the end of the vector
# include <iostream> # include <vector> using namespace std; int main(void) { vector<int> vi; for(int i=0;i<5;i++) { vi.push_back(i); } for(int i=0;i<5;i++) { cout<<vi[i]<<' '; } return 0; }
2)pop_back()
vector<int> vi; for(int i=0;i<3;i++) { vi.push_back(i); } //0,1,2 vi.pop_back();//0,1 for(int i=0;i<vi.size();i++) { cout<<vi[i]<<' ';//0,1 }
3)size()
vector<int> vi; int size=vi.size();//Returns the current number of elements
4)clear()
vector<int> vi; for(int i=0;i<5;i++) vi.push_back(i);//Add 0 in turn,1,2,3,4 vi.clear();//Clear all elements. size=0
5)insert()
vector<int> vi; for(int i=0;i<5;i++) { vi.push_back(i); } vi.insert(vi.begin()+2,-1);//-1 insert vi[2]Location
6)erase()
vector<int> vi; vi.erase(vi.beigin()+3);//Delete a single element, delete vi[3] vi.erase(vi.beigin()+1,vi.begin()+4);//Delete multiple elements, delete[ first,end]All elements between