Array

14.1 - Creating arrays


std::array is a container for fixed size array. Unlike std::vector which can have a variable size, std::array has a fixed size which is determined from the definition. To define std::array, the type and the size needs to be provided:

// Creates an array of int called numbers with the size 5.
std::array<int, 5> numbers{10, 20, 30, 40, 50};

Like std::vector, std::array supports the brace initialization. If it is defined without being initialized, the content value would be unpredictable just like uninitialized int.

Compared to a C-style array, std::array has many benefits such as knowing its size and is safer.

Task

  • Create an std::array containing int called days_in_months with the numbers of days in each month for a non-leap year:
    • Start with the type declaration std::array<int, 12>.
    • Use the brace initialization to set the values.
#include <iostream> #include <string> #include <array> int main() { std::array<std::string, 12> month_names{ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; // Create days_in_months after this line. for (int i = 0; i < 12; ++i) { std::cout << month_names[i] << ": " << days_in_months[i] << std::endl; } }