The vector is similar to array.
| Vector | Array | |
| Difference | It can be resized. Size is flexible. | Size is fixed. |
| Declaration | vector<int> v(5); | int score[5]; |
| Same -direct access |
Use index [ ] to reach individual elements. |
|
| cin>>v[3]; v[2]=100; cout<<v[2]<<" "; | cin>>score[3]; score[2]=100; cout<<score[2]<<" "; | |
How to create an object that is a vector?
| Empty vector | Five zero vector | vector with different numbers |
| #include<iostream> #include<vector> using namespace std; void main() { vector<int> vec; cout<<vec.empty()<<endl; cout<<vec.size()<<endl; } |
#include<iostream> #include<vector> using namespace std; void main() { vector<int> v(5); for(int i=0; i<v.size(); i++) cout<<v[i]<<" "; cout<<endl; } |
#include<iostream> #include<vector> using namespace std; void main() { int A[]={3,5,6,2,1} vector<int> w(A, A+5); for(int i=0; i<w.size(); i++) cout<<w[i]<<" "; cout<<endl; } |
How to resize a vector?
#include<iostream>
#include<vector>
using namespace std;
void main()
{
vector<int> vec;
vec.resize(10);
for(int i=0; i<vec.size(); i++)
cout<<vec[i]<<" ";
cout<<endl;
vec.resize(4);
for(i=0; i<vec.size(); i++)
cout<<vec[i]<<" ";
cout<<endl;
vec.resize(6,9);
for(i=0; i<vec.size(); i++)
cout<<vec[i]<<" ";
cout<<endl;
}
|
Note: 1. Create an empty vector: vector<int> vec;
|
How to update the end of vector?
#include<iostream>
#include<vector>
using namespace std;
void main()
{
vector<int> vec;
vec.push_back(8);
vec.push_back(10);
vec.push_back(12);
for(int i=0; i<vec.size(); i++)
cout<<vec[i]<<" ";
cout<<endl;
vec.pop_back();
for(i=0; i<vec.size(); i++)
cout<<vec[i]<<" ";
cout<<endl;
cout<<vec.back()<<endl;
}
|
Note: 1. Create an empty vector: vector<int> vec; 2. Add an element,
8, to the back
of array: 5. Delete the
last element: 6. Get the content
of the last element without updating the vector. |