C++ Standard Library C++ STL Library

C++ <vector> - at() Function



The C++ vector::at function returns a reference to the element of the vector at the specified position. If the specified position is not within the bounds of valid elements in the vector, the function throws an out_of_range exception.

Note: The vector::at function produces the same result as vector::operator[] function, except vector::operator[] does not check the specified position against bounds of valid elements in the vector.

Syntax

reference at (size_type n);
const_reference at (size_type n) const;
reference at (size_type n);
const_reference at (size_type n) const;

Parameters

n Specify position of the element in the vector.

Return Value

The element at the specified position in the vector.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::at function returns a reference to the element of the vector called MyVector at the specified positions.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30};
  MyVector.push_back(40);
  MyVector.push_back(50);

  cout<<"The vector contains:";
  for(int i = 0; i < MyVector.size(); i++)
    cout<<" "<<MyVector.at(i);

  return 0;
}

The output of the above code will be:

The vector contains: 10 20 30 40 50

❮ C++ <vector> Library