Vectors
Vectors
Vectors are used to store elements of similar data types. However, unlike
arrays, the size of a vector can grow dynamically.
That is, we can change the size of the vector during the execution of a
program as per our requirements.
Declaration And Initialization Of Vectors:
Before using vectors, make sure that you have included it’s header file.
#include <vector>
return 0; return 0;
} }
Element Access Method
To get the element at begin:
v.front();
r n
#include <vector>
using namespace std;
In a to Of
Ve rs
int main(){
cto
rs
vector<int> v;
for (int i = 1; i <= 5; i++)
v.push_back(i);
return 0;
}
Some Basic Functions
To know the size of the vector :
v.size();
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> v= {2,5,10,1,50,26,30};
int minimumElement= *min_element(v.begin(),v.end());
int minInd= min_element(v.begin(),v.end())-v.begin();
int maximumElement= *max_element(v.begin(),v.end());
int maxInd= max_element(v.begin(),v.end())-v.begin();
cout<<"Minimum element is :"<<minimumElement<<" at index "<<minInd<<endl;
cout<<"Maximum element is :"<<maximumElement<<" at index "<<maxInd<<endl;
return 0;
}
Sorting
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> v= {2,5,10,1,50,26,30};
sort(v.begin(),v.end());
for (int i=0; i<7; i++){
cout<<v[i]<<" ";
}
cout<<endl;
return 0;
}
upper_bound And lower_bound
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> v= {1,2,3,4,6,7,9};
int lower1= *lower_bound(v.begin(),v.end(),4);
int lower2= *lower_bound(v.begin(),v.end(),5);
int upper1= *upper_bound(v.begin(),v.end(),4);
int upper2= *upper_bound(v.begin(),v.end(),5);
cout<<"Lower bound of 4 is "<<lower1<<endl;
cout<<"Lower bound of 5 is "<<lower2<<endl;
cout<<"Upper bound of 4 is "<<upper1<<endl;
cout<<"Upper bound of 5 is "<<upper2<<endl;
return 0;
}
Reversing
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<int> v= {2,5,10,1,50,26,30};
reverse(v.begin(),v.end());
for (int i=0; i<7; i++){
cout<<v[i]<<" ";
}
cout<<endl;
return 0;
}
Sum : Accumulate function
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> v= {2,5,10,1,50,26,30};
int sum= accumulate(v.begin(),v.end(),0);
cout<<"THE sum is: "<<sum<<endl;
cout<<endl;
return 0;
}
Find Function
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> v= {2,5,10,1,50,26,30};
int val= find(v.begin(),v.end(),1)-
v.begin();
cout<<val;
cout<<endl;
return 0;
}
Count Function
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> v= {2,5,1,10,1,50,26,1,1,30};
int val= count(v.begin(),v.end(),1);
cout<<val;
cout<<endl;
return 0;
}
Finding the factors:
O(N) O(sqrt(N
))