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

C++ Usage and Example of Deque at()

C++ Deque (Double-ended Queue)

C ++ The at() function of Deque is used to access the element at the specified position pos.

Note: If pos is greater than the size of the container, this function will throw an exception, that is, 'out of range'.

Syntax

reference at(size_type pos);

Parameter

pos: it defines the position of the element to be returned.

Where, size_type is an unsigned integer type.

Return value

It returns a reference to the specified element.

Example1

Let's look at a simple example

#include <iostream>
#include<deque>
using namespace std;
int main()
{
   deque<char> ch = {'n', 'h', 'o', 'o', 'o', '.', 'c', 'o', 'm'};
   for(int i = 0; i < ch.size(); i++)
   cout << ch.at(i);
   return 0;
}

Output:

oldtoolbag.com

Example2

Let's look at a simple example

#include <iostream>
#include<deque>
using namespace std;
int main()
{
   deque<int> k={1,2,3,4,5};
   cout << k.at(5);
   return 0;
}

Output:

terminate called after throwing an instance of 'std::out_of_range'

In this example, the at() function attempts to access an element beyond the size of the container. Therefore, it will throw an exception, namely out of range.

C++ Deque (Double-ended Queue)