There is no pushfront member function in STL vector or in ou
There is no push_front() member function in STL vector or in our own Vector class, why? Give your own implementation of push_front() member function for Vector. What is the time complexity of the function?
Solution
Hi, Please find my explanation.
Please let me know in case of any issue.
We do not have push_front() method in STL Vector because it takes O(n) time to add an element at front.
To add an elements at front, we have to shift all elemnts of vector left by one to create a space at front.
void push_front(vector<int> list, int item){
// adding a dummy value at end to create a extra space in list(vector)
list.push_back(itam);
// now shift all elements left
for(int i=list.size()-1; i>0; i--)
list[i] = list[i-1];
// now adding an elements at front
list[0] = item;
}
