1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
#include <iostream>
#include <array>
template <typename T, size_t N>
std::ostream& operator<<(std::ostream&, std::array<T, N> const&);
template<typename T, size_t R, size_t C>
std::ostream& operator<<(std::ostream&, std::array<std::array<T, C>, R> const&);
int main()
{
const size_t row_size = 4;
const size_t col_size = 3;
// creating a C-style array is easy with an initializer list
// short myArray[row_size][col_size] = { {-501, 206, 2011}, {989, 101, 206}, {303, 456, 596}, {123, 543, 108} };
// notice the dimension sizes are reversed when initializing a multidimensional std::array,
// with an extra set of brackets required for the initializer list
std::array<std::array<short, col_size>, row_size> my2DArray = { { {-501, 206, 2011},
{989, 101, 206},
{303, 456, 596},
{123, 543, 108} } };
std::cout << "The 2D STL array contents are:\n";
for (size_t row = 0; row < row_size; row++)
{
for (size_t col = 0; col < col_size; col++)
{
std::cout << my2DArray[row][col] << '\t';
}
std::cout << '\n';
}
std::cout << '\n';
std::cout << "Let's display that 2D array again:\n";
// using range-based for loops for output
for (const auto& r : my2DArray)
{
for (const auto& c : r)
{
std::cout << c << '\t';
}
std::cout << '\n';
}
std::cout << '\n';
// overloading operator<< makes outputting 2D arrays really easy
std::cout << "Let's try that again:\n";
std::cout << my2DArray << '\n';
// properly overloaded operator<< works with 1D arrays as well
std::array<int, 5> my1DArray = { 34, 56, -21, 5002, 365 };
std::cout << "Here's a 1D array:\n";
std::cout << my1DArray << '\n';
}
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& os, std::array<T, N> const& arr)
{
for (auto const& x : arr)
{
os << x << '\t';
}
return os;
}
template<typename T, size_t R, size_t C>
std::ostream& operator<<(std::ostream& os, std::array<std::array<T, C>, R> const& arr)
{
for (const auto& x : arr)
{
std::cout << x << '\n';
}
return os;
}
|