Listing 5
#include <array>
#include <stdexcept>
#include <iostream>
using std::tr1::array;
using std::cout; using std::out_of_range;
const int size = 7;
typedef array<int, size> array_t;
void show(const array_t& array, int idx)
{ // access array element with explicit range check
cout << "Element[" << idx << "] is ";
if (idx < 0 || array.size() <= idx)
cout << "[index out of range]\n";
else
cout << array[idx] << '\n';
}
void show_at(const array_t& array, int idx)
{ // access array element with implicit range check
try { // try to access element at idx
cout << "Element[" << idx << "] is ";
cout << array.at(idx) << '\n';
}
catch(const out_of_range&)
{ // catch exception on invalid index
cout << "[index out of range]\n";
}
}
int main()
{ // demonstrate us of member function at()
array_t arr = { 1, 1, 2, 3, 5 };
show(arr, 3);
show_at(arr, 3);
show(arr, 5);
show_at(arr, 5);
show(arr, 8);
show_at(arr, 8);
return 0;
}