C++ Vector at() function

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.

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

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.