The safe C++ at() member function automatically checks whether array index is within the bounds of valid elements in the container, throwing an out_of_range exception if the array index is not, i.e. if the array index is greater than or equal to its array size.
The member function at() does check against bounds.
Here's a C++ program that uses the array data structure and at() member function.
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<string, 12> month_names = { "January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
};
cout << "month_names.at(11): " << month_names.at(11) << endl;
// terminate called after throwing an instance of std::out_of_range exception
cout << "month_names.at(13): " << month_names.at(13) << endl;
return 0;
}
No comments:
Post a Comment