What is the vector::at() function in C++?

Introduction

The at() function returns a reference to the element present at the index number given as a parameter.

If the position or index number is not present in the vector, i.e., it is out of the range, then the at() function throws an out-of-range exception.

Syntax

The syntax of the vector::at() function is shown below:

reference at(unsigned int);

Parameters

The at() function accepts the position or index number as a single parameter of type unsigned int. This position or index number specifies the element that needs to be returned.

Return value

The at() function returns the element from the specified location. If that location is invalid, the function throws an out-of-range exception.

Code

Let’s have a look at the code.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
vec.push_back(6);
vec.push_back(2);
cout << "Element of the vector at position 3 is: " << vec.at(3);
return 0;
}

Explanation

  • In line 2, we include the C++ standard header file for input output stream (iostream) that is used to read and write from streams.

  • In line 3, we include the header file for the C++ standard vector, which includes all the functions and operations related to the Vector container.

  • In line 4, we use the standard (std) namespace, which means we use all of the things within the std namespace.

  • In line 7, we declare the integer type Vector container named vec.

  • From lines 9-13, we push back the different elements to the vector container vec.

  • In line 15, we print the result of the at() function, which returns the element of the vector at the specified position. In this example, we specify the position as 3, and hence the output is 6. This means that the element at index 3 is 6.

In this way, we can easily get the first element present in a vector.

Free Resources