English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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.
reference operator[](int pos);
pos: It defines the position of the element to be accessed.
It returns a reference to the element at position pos in the deque container.
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.
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.