Open In App

How to Access the First Element of a Deque in C++?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, deques also called double-ended queues are sequence containers that can perform insertions and deletions on both ends. In this article, we will learn how to access the first element of a deque in C++.

Example:

Input:
myDeque = {1,2,3,4,5}

Output: 
Deque Elements: 1 2 3 4 5
First Element: 1

Accessing the First Element of a Deque in C++

To access the first element of a std::deque in C++, we can use the std::deque::front() method which returns a reference to the first element of the deque. This function is suitable for accessing and manipulating the first element without modifying the deque’s structure.

Syntax

deque_name.front();

Here:

  • deque_name: Denotess the deque container.
  • front(): This denotes the function used to access the first element of the deque.

C++ Program to Access the First Element of a Deque

The below program demonstrates how we can access the first element of a deque in C++.

C++
// C++ Program to illustrates how to access the first
// element of a deque
#include <deque>
#include <iostream>
using namespace std;

int main()
{

    // Initializing a deque
    deque<int> dq = { 1, 2, 3, 4, 5 };

    // Printing deque elements
    cout << "Deque Elements:";
    for (int num : dq) {
        cout << " " << num;
    }
    cout << endl;

    // Accessing the first element using front()
    int frontElement = dq.front();

    // Printing the first element
    cout << "First Element: " << frontElement << endl;

    return 0;
}

Output
Deque Elements: 1 2 3 4 5
First Element: 1

Time Complexity: O(1)
Auxilliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads