1. Usage of begin() and end() functions, front() and back()
- begin function
Function prototype:
iterator begin();
const_iterator begin();
Function:
Returns an iterator of the start element in the current vector container.
- end function
Function prototype:
iterator end();
const_iterator end();
Function:
Returns an iterator of the last element in the current vector container.
- front function
Function prototype:
reference front();
const_reference front();
Function:
Returns the reference of the starting element in the current vector container.
- back function
Function prototype:
reference back();
const_reference back();
Function:
Returns the reference to the last element in the current vector container.
2. Usage of begin() and end() functions, front() and back()
(1) Header file #include.
(2) Create a vector object, vector vec;
(3) Insert numbers at the tail: vec.push_back(a);
delete numbers at the tail: vec.pop_back(b);
(4) Use subscripts to access elements,
cout<<vec[0]<<endl;
//记住下标是从0开始的。
(5) Access elements using iterators
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();
Reference document: That year Cong Cong's blog