Push: to apply force to (someone or something) so that it moves in front of one. Synonyms: drive, propel, shove. Best Success Lessons Considered the Granddaddy of all Self Help books, Pushing to the Front is an amazing collection of personal development guidance. Orison Swett Marden: Pushing To The Front Orison Swett Marden is the author of the timeless classic, Pushing To The Front – the ultimate American success book. Please accept this free gift, a copy of the classic book on the secrets of leadership and success, Pushing To The Front. We appreciate you taking the time to visit our website.
Write code to implement pop_front operation for a vector in C++. The pop_front operation should remove the first element from the vector and maintain the order of remaining elements.
Pushing The Rope
We know that std::vector
only supports push_back
and pop_back
operations. Both operations runs in constant time. The pop_front
operation will take at-least O(n) time since the vector is backed by an array and all the remaining elements needs to be shifted by one position to the left to preserve the order. If number of pop_front
operation is more, std::list
container should be preferred which is implemented as double-ended queue (deque).
So pop_front
operation will take linear time and should called only if the vector contains only small number of elements. Here’s one feasible implementation of the pop_front
function which simply erases the first element of the vector using vector::erase
method. The vector::erase
function requires an iterator pointing to the element to be removed from the vector and we can get an iterator to the first element of a vector by calling vector::begin
.
2 4 6 8 10 12 14 16 18 20 | #include <vector> template<typenameT> { v.erase(v.begin()); } intmain() std::vector<int>nums={1,2,3,4,5}; std::cout<<i<<' '; return0; |
Output:
2 3 4 5
Luckily if we don’t need to maintain the order of the remaining elements in the vector, we have a constant time solution which includes moving the last element of the vector to the front. This can be done with the help of std::move
function.
2 4 6 8 10 12 14 16 18 20 22 | #include <vector> template<typenameT> { v.front()=std::move(v.back()); } { pop_front(nums); for(inti:nums) } |
Output:
5 2 3 4
(4 votes, average: 5.00 out of 5)
Loading...
Thanks for reading.
Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP and many more popular programming languages.
Like us? Refer us to your friends and help us grow. Stay Safe. Happy coding :)
JavaScript gives us four methods to add or remove items from the beginning or end of arrays:
pop(): Remove an item from the end of an array
pop() returns the removed item.
push(): Add items to the end of an array
push() returns the new array length.
shift(): Remove an item from the beginning of an array
shift() returns the removed item.
unshift(): Add items to the beginning of an array
unshift() returns the new array length.