STL-deque in C++ Programming


Deque is a shorthand for doubly ended queue. Deque allows fast insertion and deletion at both ends of the queue.

This program demonstrates the use of deque (double-ended queue) container in C++ STL.

First, the deque container is declared and initialized with a single element 10 using the initializer list syntax.

Then, three more elements are added to the deque using push_back() and push_front() functions. The elements are printed using a range-based for loop.

The program also demonstrates the usage of some common member functions of the deque container:

  • size(): returns the number of elements in the deque.
  • empty(): returns true if the deque is empty, false otherwise.
  • at(): returns the element at the specified index. If the index is out of range, an exception is thrown.
  • front(): returns the first element of the deque.
  • back(): returns the last element of the deque.
  • pop_back(): removes the last element of the deque.
  • pop_front(): removes the first element of the deque.

Finally, the deque is printed again using a range-based for loop after removing the first and last elements.

Source Code

#include<iostream>
#include<deque>
using namespace std;
//STL-Deque in C++
int main()
{
    deque<int> d={10};
    d.push_back(25);
    d.push_front(45);
    for(int x : d){
	cout<<" "<<x;
    }
    cout<<endl;
    cout<<"Deque Size : "<<d.size()<<endl;
    cout<<"Deque Empty or Not : "<<d.empty()<<endl;
    cout<<"Deque Element At 2 Index : "<<d.at(2)<<endl;
    cout<<"Deque First Element: "<<d.front()<<endl;
    cout<<"Deque Last Element: "<<d.back()<<endl;
    d.pop_back();
    d.pop_front();
    for(int x : d){
	cout<<" "<<x;
    }
    return 0;
}
 

Output

 45 10 25
Deque Size : 3
Deque Empty or Not : 0
Deque Element At 2 Index : 25
Deque First Element: 45
Deque Last Element: 25
 10
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples