Deque Operator Function

C++ Deque operator

C++ Deque operator function is used to access the element at specified position pos. If position pos is greater than the size of container then it returns a value 0.

Difference between operator & at

When position pos is greater than the size of the container then operator function returns a value 0 while at function throws an exception i.e out of range.

Syntax

Example

reference operator[] (int pos);

Parameter

pos : It defines the position of an element which is to be accessed.

Return value

It returns a reference to an element at position pos in 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 example, operator function access each element of deque a.

Example 2

Let's see a simple example when pos is out of 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 example, operator function tries to access the position which is greater than the size of the container. Therefore, it returns 0.

Input Required

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