Deque Operator Function - C++ Programming Tutorial
C++ Course / STL Queue & Stack / Deque Operator Function

Deque Operator Function

BLUF: Mastering Deque Operator Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Deque Operator Function

C++ is renowned for its efficiency. Learn how Deque Operator Function enables low-level control and high-performance computing in the tutorial below.

The operator function in C++ Deque is utilized to retrieve the element located at a specific position referred to as pos. In case pos exceeds the container's size, it will return a value of 0.

Difference between operator__PRESERVE_5__ & at

When the index pos exceeds the container's size, the operator function yields a value of 0, whereas the at function raises an out-of-range exception.

Syntax

Example

reference operator[] (int pos);

Parameter

It specifies the location of an element that needs to be retrieved.

Return value

It provides a reference to an element located at the specified position pos within the deque container.

Example 1

Let's see a simple example

Example

#include <iostream>
#include<deque>
using namespace std;
int main()
{
   
  deque<string> a={"mango","is","my","favorite","fruit"};
   for(int i=0;i<a.size();i++)
  {
      cout<<a.operator[](i);
      cout<<" ";
  }
    return 0;
}

Output:

Output

mango is my favorite fruit

In this instance, the operator method is utilized to access every element within deque a.

Example 2

Let's explore a basic scenario where the position (pos) is beyond the allowable range.

Example

#include <iostream>
#include<deque>
using namespace std;
int main()
{
     deque<int> a={1,2,3,4,5,6};
  
  cout<<a.operator[](7);
  return 0;
}

Output:

In this instance, the operator function attempts to retrieve a position beyond the container's size, resulting in a return value of 0.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience