In this C++ tutorial, you will learn about vector::at() function, its syntax, and how to use this function to get the element at specific index, with example programs.

C++ Vector at() function

vector::at() function returns the reference to element at specified index/position in the vector.

Examples

In the following examples, we will learn how to get reference to the element at given index in a vector.

ADVERTISEMENT

1. Get element at index = 5 in string vector

In the following C++ program, we define a vector of integers, and get the reference to the element at index=5.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> nums{ 1, 2, 4, 8, 16, 32, 64 };
    int &x = nums.at( 5 );
    cout << "Element at index=5 is " << x << endl;
}

Output

Element at index=5 is 32

2. Get element at index = 2 in string vector

In the following C++ program, we define a vector of integers, and get the reference to the element at index=2.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> arr{ "apple", "banana", "cherry", "mango" };
    string &x = arr.at( 2 );
    cout << "Element at index=2 is " << x << endl;
}

Output

Element at index=2 is cherry

Conclusion

In this C++ Tutorial, we learned how to get reference to element at specific index of a vector using at() function.