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

C++ Usage and examples of vector at()

C++ Vector

Returns the data pointed to by the index. If the passed index is out of range, throws out_of_range.

Syntax

Create vector v, k is the index position. The syntax is:

vector<object_type> v;
v.at(k);

Parameter

k: k defines the index position of the element to be returned by the at() function.

Return value

It returns the element at the specified position.

The figure below shows how the at() function works

If i = 0:



If i = 3:



Example

Let's see a simple example.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v1{1,2,3,4};
for(int i = 0; i < v1.size();i++)
cout << v1.at(i);
return 0; 
}

Output:

1234

In this example, the at() function accesses the elements of the vector.

C++ Vector