example5_bounds_checking_with_at.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <iostream>
#include <array>

int main() {
    std::array<int, 5> myArray = {10, 20, 30, 40, 50};

    try {
        std::cout << "Element at index 2: " << myArray.at(2) << std::endl;
        std::cout << "Element at index 5: " << myArray.at(5) << std::endl;  // This will throw an exception
    } catch (const std::out_of_range& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}
Back to std_array