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