Array Bounds Check Using At

Programmer lets the library perform bound checks using the at method.

/* * Read some integers into an array, then echo them. */ #include <iostream> #include <array> #include <stdexcept> int main() { // Read them in, using library bounds checking. std::array<int, 10> arr; int sub = 0; std::cout << "Enter some integers: " << std::endl; try { int val; for(; std::cin >> val; ++sub) { arr.at(sub) = val; } } catch(std::out_of_range &e) { std::cout << "Array full; reading stopped." << std::endl; } int num = sub; // Print them back out again. Since we made sure not to overfill // the array on input, we know that sub cannot become out of bounds // in this loop. So we use plain [] for efficiency. std::cout << "===============" << std::endl; for(int sub = 0; sub < num; ++sub) std::cout << arr[sub] << " "; std::cout << std::endl; }