Saturday

Safe C++ example using array data structure and at member function

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:

C++32 (or C++2e), C++ 2032, Cpp 2032, g++ 2032

  Subject: C++ 2032 3 Code example for ? 2 Approximate feature suggestions: - to complete C++29 or C++ 2029 1 Web links, references Wandbox,...