Open In App

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

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++ STL, we have a deque container which is a double-ended queue that allows us to add or remove elements from both ends. In this article, we will learn how to access the last element in a deque in C++.

For Example,

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

Output:
Last Element: 6

Accessing the Last Element in a Deque in C++

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

Syntax to Use std::back

dequeName.back();

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

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

C++
// C++ program to demonstrate how to access the last element
// of a deque
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    // Initializing a new deque
    deque<int> myDeque = { 1, 2, 3, 4, 5 };

    // Using back() function to retrieve the last element
    int lastElement = myDeque.back();

    // Printing the last element
    cout << "The last element is: " << lastElement << endl;

    return 0;
}

Output
The last element is: 5

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




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads