C++ <deque> - operator[]() Function
The C++ deque::operator[] function returns a reference to the element of the deque at the specified position. If the specified position is not within the bounds of valid elements in the deque, the function does not throw any exception.
Note: The deque::operator[] function produces the same result as deque::at function, except deque::at do check the specified position against bounds of valid elements in the deque.
Syntax
reference operator[] (size_type n); const_reference operator[] (size_type n) const;
reference operator[] (size_type n); const_reference operator[] (size_type n) const;
Parameters
n |
Specify position of the element in the deque. |
Return Value
The element at the specified position in the deque.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the deque::operator[] function returns a reference to the element of the deque at the specified position.
#include <iostream> #include <deque> using namespace std; int main (){ deque<int> MyDeque (5); int size = MyDeque.size(); for(int i=0; i<size; i++) MyDeque[i] = 100*(i+1); cout<<"MyDeque contains: "; for(int i=0; i<size; i++) cout<<MyDeque[i]<<" "; return 0; }
The output of the above code will be:
MyDeque contains: 100 200 300 400 500
❮ C++ <deque> Library