English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and example of Deque operator[]()

C++ Deque (Double-ended Queue)

C ++ The Deque operator [] function is used to access the element at the specified position pos. If the position pos is greater than the size of the container, it will return 0.

The difference between operator[]() and at()

When the position pos is greater than the size of the container, the operator []() function will return 0, and the at() function will throw an exception, i.e., out of range.

Syntax

reference operator[](int pos);

Parameter

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

Return value

It returns a reference to the element at position pos in the deque container.

Example1

Let's look at a simple 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:

mango is my favorite fruit

In this example, the operator []() function accesses each element of the deque a.

Example2

Let's look at a simple example to illustrate that pos is out of range.

#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:

0

In this example, the operator []() function attempts to access a position greater than the container size. Therefore, it returns 0.

C++ Deque (Double-ended Queue)