Cpp Libs Vector At
[ C++ Container Class ](#)
* * *
Among all the ways to access vector elements, `at` is the safest one because it provides **boundary checking**.
`at` is a member function of the container class, used to **return the element at the specified position** while performing boundary checking. If the index is out of bounds, it throws a `std::out_of_range` exception.
`at` implements safe element access, allowing you to catch and handle out-of-bounds errors at runtime.
**Word Meaning**: `at` means "at the position", i.e., getting the element at the specified position.
* * *
## Basic Syntax and Parameters
`at` is a member function of the container class, so you need to have a container object first, and then call it using the dot operator `.`.
### Syntax Format
reference at(size_type pos); const_reference at(size_type pos) const;
### Parameter Description
* **Parameter**: `pos`
* Type: `size_type` (unsigned integer type, usually `size_t`)
* Description: The position (index) of the element to access. Index starts from 0, and the maximum valid index is `size() - 1`.
### Function Description
* **Return Value**: Returns a **reference** to the element at the specified position. If the container is a const container, it returns a const reference.
* **Effect**: Returns the element at the specified position. If the index exceeds the valid range (`pos >= size()`), it throws a `std::out_of_range` exception.
* **Difference from `operator[]`**: `at` performs boundary checking, while `operator[]` does not perform boundary checking (out-of-bounds behavior is undefined).
* * *
## Examples
Let's thoroughly master the usage of `at` through a series of examples from simple to complex.
### Example 1: Basic Usage - Accessing Elements
## Example
#include
#include
#include // Include exception handling header
int main(){
// 1. Create a vector and add some elements
std::vector numbers ={10, 20, 30, 40, 50};
std::cout<<"vector size is: "<< numbers.size()<< std::endl;
// 2. Use at to access elements
std::cout<<"First element (at(0)): "<< numbers.at(0)<< std::endl;
std::cout<<"Second element (at(1)): "<< numbers.at(1)<< std::endl;
std::cout<<"Third element (at(2)): "<< numbers.at(2)<< std::endl;
std::cout<<"Last element (at(4)): "<< numbers.at(4)<< std::endl;
// 3. Use a loop to access all elements
std::cout<<"All elements: ";
for(size_t i =0; i < numbers.size();++i){
std::cout<< numbers.at(i)<<" ";
}
std::cout<< std::endl;
return 0;
}
**Expected Output:**
vector size is: 5First element (at(0)): 10Second element (at(1)): 20Third element (at(2)): 30Last element (at(4)): 50All elements: 10 20 30 40 50
**Code Explanation:**
1. `numbers.at(0)` returns the first element `10` (index starts from 0).
2. `numbers.at(4)` returns the last element `50` (because `size()` is 5, valid indices are 0-4).
3. Using a loop with `at` can safely traverse all elements.
### Example 2: Catching Out-of-Bounds Exceptions
The main advantage of `at` is that it can throw exceptions, allowing us to handle out-of-bounds errors.
## Example
#include
#include
#include
int main(){
std::vector numbers ={10, 20, 30};
// Try to access out-of-bounds position
try{
std::cout<<"Trying to access at(10)..."<< std::endl;
int value = numbers.at(10);// This will throw an exception
std::cout<<"Value: "<< value << std::endl;
}
catch(const std::out_of_range& e){
std::cout<<"Exception caught: "<< e.what()<< std::endl;
}
// Normal access
try{
std::cout<<"Access at(2): "<< numbers.at(2)<< std::endl;
}
catch(const std::out_of_range& e){
std::cout<<"Exception caught: "<< e.what()<= this->size() (which is 3)Access at(2): 30
**Code Explanation:**
* When accessing `at(10)`, since the index is out of range, a `std::out_of_range` exception is thrown.
* `catch(const std::out_of_range& e)` catches the exception, and `e.what()` returns the description of the exception.
* Normal index access does not throw exceptions.
### Example 3: Comparison Between at and operator[]
Compare the behavioral differences between `at` and `operator[]`.
## Example
#include
#include
#include
int main(){
std::vector numbers ={10, 20, 30};
std::cout<<"Using at() to access elements:"<< std::endl;
// at() performs boundary checking
for(size_t i =0; i <= numbers.size();++i){
try{
std::cout<<"at("<< i <<") = "<< numbers.at(i)<< std::endl;
}
catch(const std::out_of_range& e){
std::cout<<"at("<< i <<") out of bounds!"<< std::endl;
}
}
std::cout<<"n Using operator[] to access elements:"<< std::endl;
// operator[] does not perform boundary checking, out-of-bounds behavior is undefined
for(size_t i =0; i <= numbers.size();++i){
std::cout<<"numbers["<< i <<"] = "<< numbers<< std::endl;
}
return 0;
}
**Code Explanation:**
* `at()` throws an exception when out of bounds, and you can choose to catch and handle it.
* `operator[]` has undefined behavior when out of bounds, which may return garbage values, crash, or produce other unpredictable results.
* In production code, for safety, it is recommended to use `at()` instead of `operator[]`, especially when the index comes from user input or external data.
### Example 4: Modifying Element Values
`at` returns a reference, so it can be used to modify element values.
## Example
#include
#include
int main(){
std::vector numbers ={10, 20, 30};
std::cout<<"Before modification: ";
for(size_t i =0; i < numbers.size();++i){
std::cout<< numbers.at(i)<<" ";
}
std::cout<< std::endl;
// Use at() to get reference and modify elements
numbers.at(0)=100;
numbers.at(1)=200;
numbers.at(2)=300;
std::cout<<"After modification: ";
for(size_t i =0; i < numbers.size();++i){
std::cout<< numbers.at(i)<<" ";
}
std::cout<< std::endl;
return 0;
}
**Expected Output:**
Before modification: 10 20 30After modification: 100 200 300
**Code Explanation:**
* `numbers.at(0) = 100;` modifies the value of the first element through reference.
* This demonstrates that `at()` returns a modifiable lvalue reference.
* * C++ Container Class ](#)
YouTip