Open In App

deque::push_front() in C++ STL

Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed.

deque::push_front()

push_front() function is used to push elements into a deque from the front. The new value is inserted into the deque at the beginning, before the current first element and the container size is increased by 1.

Syntax :

dequename.push_front(value)
Parameters :
The value to be added in the front is 
passed as the parameter
Result :
Adds the value mentioned as the parameter 
to the front of the deque named as dequename

Examples:

Input : deque{1, 2, 3, 4, 5};
        deque.push_front(6);
Output : 6, 1, 2, 3, 4, 5

Input : deque{5, 4, 3, 2, 1};
        deque.push_front(6);
Output :6, 5, 4, 3, 2, 1

Errors and Exceptions

1. Strong exception guarantee – if an exception is thrown, there are no changes in the container.
2. If the value passed as argument is not supported by the deque, it shows undefined behaviour.




// CPP program to illustrate
// push_front() function
#include <deque>
#include <iostream>
using namespace std;
  
int main()
{
    deque<int> mydeque{ 1, 2, 3, 4, 5 };
    mydeque.push_front(6);
  
    // deque becomes 6, 1, 2, 3, 4, 5
  
    for (auto it = mydeque.begin();
         it != mydeque.end(); ++it)
        cout << ' ' << *it;
}

Output:

6 1 2 3 4 5

Time Complexity : O(1)

Application
Given an empty deque, add integers to it using push_front() function and then calculate its size.

Input  : 1, 2, 3, 4, 5, 6
Output : 6

Algorithm
1. Add elements to the deque using push_front() function
2. Check if the size of the deque is 0, if not, increment the counter variable initialised as 0, and pop the front element.
3. Repeat this step until the size of the deque becomes 0.
4. Print the final value of the variable.




// CPP program to illustrate
// Application of push_front() function
#include <deque>
#include <iostream>
using namespace std;
  
int main()
{
    int count = 0;
    deque<int> mydeque;
    mydeque.push_front(1);
    mydeque.push_front(2);
    mydeque.push_front(3);
    mydeque.push_front(4);
    mydeque.push_front(5);
    mydeque.push_front(6);
    while (!mydeque.empty()) {
        count++;
        mydeque.pop_front();
    }
    cout << count;
    return 0;
}

Output:

6

Article Tags :
C++