vector::at() in C++ STL (original) (raw)
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 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++:
Table of Content
Syntax of vector at()
The vector at() is a member method of std::vector class defined inside ****** header file.
v.**at(i);
**Parameters
- **i: 0-based position of the element in the vector.
**Return Value
- Returns the reference to the element at given index.
- If the index is out of bounds, an **std::out_of_range exception is thrown.
Examples of vector at()
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 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 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;}
`
Output
Exception: vector::_M_range_check: __n (which is 5) >= this->size() (which is 4)