In C++, vector is a very useful container.
Function: It can store various types of objects like a container. Simply put, a vector is a dynamic array that can store any type, and can increase and compress data.
Vector is part of the C++ Standard Template Library, which is a multi- functional library of template classes and functions that can manipulate a variety of data structures and algorithms.
pay attention:
There are a few things to keep in mind when using vectors:
1. If the length of the vector you want to represent is long (you need to save a lot of numbers inside the vector), it is easy to cause memory leaks, and the efficiency will be very low;
2. When Vector is used as a parameter or return value of a function, you need to pay attention to its writing:
double Distance(vector<int>&a, vector<int>&b) The "&" in it must not be less! ! !
Example: vector<int>test;
//Create a vector, int is the data type of the array element, test is the dynamic array name
The simple usage is as follows:
vector<int>test;//Create a vector
test.push_back(1);
test.push_back(2);//Push 1 and 2 into the vector, so test[0] is 1, test[1] is 2
Examples I have seen:
vector<vector<Point2f> > points; //Define a two-dimensional array
points[0].size(); //refers to the number of columns in the first row
1. Basic operation
(1) Header file #include<vector>.
(2) Create a vector object, vector<int> vec;
(3) Insert numbers at the end: vec.push_back(a);
(4) Use subscripts to access elements, cout<<vec[0]<<endl; remember that subscripts start from 0.
(5) Use an iterator to access elements.
vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
cout<<*it<<endl;
(6) Insert elements: vec.insert(vec.begin()+i,a); insert a before the i+1th element;
(7) Delete element: vec.erase(vec.begin()+2); delete the third element
vec.erase(vec.begin()+i,vec.end()+j); delete interval [i,j-1]; interval starts from 0
(8) Vector size: vec.size();
(9) Clear: vec.clear();
2. Important Notes
The elements of the vector can not only be int, double, string, but also a structure, but pay attention: the structure must be defined as global, otherwise an error will occur.
#include<stdio.h> #include<algorithm> #include<vector> #include<iostream> using namespace std; typedef struct rect { int id; int length; int width; // For the vector element is a structure, a comparison function can be defined inside the structure, and the following is sorted in ascending order by id, length, and 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; intmain () { 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; }