AT()

The at() function is a member of containers like std::vector, std::array, and std::string. It provides a safe way to access elements by index. Unlike the subscript operator ([]), which performs no bounds checking, at() checks whether the given index is within the valid range of the container. If the index is out of range, it throws an std::out_of_range exception, making it especially useful when you want safer code and better error handling. Although at() may introduce a slight performance overhead due to the bounds check, it is a preferred choice in situations where robustness and safety are more important than raw speed.

#include <iostream>
#include <vector>   // for std::vector
#include <array>    // for std::array
#include <string>   // for std::string

using namespace std;

int main() {
    // --- std::vector example ---
    vector<int> numbers = {10, 20, 30};
    cout << "Vector element at index 1: " << numbers.at(1) << endl;

    // --- std::array example ---
    array<int, 3> fixedNumbers = {100, 200, 300};
    cout << "Array element at index 2: " << fixedNumbers.at(2) << endl;

    // --- std::string example ---
    string word = "Hello";
    cout << "String character at index 4: " << word.at(4) << endl;

    // --- Demonstrating out_of_range exception ---
    try {
        cout << "Accessing invalid index in vector: " << numbers.at(5) << endl;
    } catch (out_of_range &e) {
        cout << "Caught exception: " << e.what() << endl;
    }

    return 0;
}

OUTPUT:
 Vector element at index 1: 20
Array element at index 2: 300
String character at index 4: o
Accessing invalid index in vector: Caught exception: vector::_M_range_check: __n (which is 5) >= this->size() (which is 3)

Last updated