Last Updated : 19 Nov, 2024
In C++, vector at() is a built-in method used to access an element in a vector using index. It is the only access method that performs bound checking before accessing the element to confirm whether the given index lies is within the vector.
Let’s take a quick look at a simple example that uses vector at() method:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 3, 4, 9};
// Accessing the element of second index
cout << v.at(2);
return 0;
}
This article covers the syntax, usage, and common queries of vector at() method in C++:
Syntax of vector at()The vector at() is a member method of std::vector class defined inside <vector> header file.
v.at(i);
Parameters
Return Value
The below examples illustrate the common uses of vector at() method:
Modifying Elements Using vector at() C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 3, 4, 9};
// Modify the element at 2nd index
v.at(2) = 7;
cout << v.at(2);
return 0;
}
Catching Out-of-Range Exceptions with vector at() C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 3, 4, 9};
try {
// Attempting to access out of range index
cout << v.at(5) << endl;
} catch (const out_of_range& e) {
cout << "Exception: " << e.what() << endl;
}
return 0;
}
Exception: vector::_M_range_check: __n (which is 5) >= this->size() (which is 4)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4