A interesting challenge was brought to my attention: to "flip" an array. I thought it might be more convenient if its bounds were symmetrical, say [-N..N]
instead of [0 .. 2N + 1]
.
Now I'm curious about what could be done to make this Array more mature. Say, like a Boost component.
#include <cassert>
#include <iostream>
#include <algorithm>
template <typename T, int LoBound, int HiBound> class Array {
T arr_[HiBound - LoBound + 1];
public:
Array()
{
std::fill(arr_, arr_ + sizeof(arr_) / sizeof(arr_[0]), T{});
}
Array(const Array& other)
:arr_(other.arr_)
{}
Array(std::initializer_list<T> initList)
{
std::copy(initList.begin(), initList.end(), arr_);
}
T& operator[](int ix)
{
assert(ix >= LoBound && ix <= HiBound);
return arr_[ix - LoBound];
}
const T& operator[](int ix) const
{
assert(ix >= LoBound && ix <= HiBound);
return arr_[ix - LoBound];
}
};
int main()
{
enum {LoBound = -2, HiBound = 2};
using A1D = Array<int, LoBound, HiBound>;
Array<A1D, LoBound, HiBound> arr =
{ A1D{ 1, 2, 3, 4, 5},
A1D{ 6, 7, 8, 9, 10},
A1D{11, 12, 13, 14, 15},
A1D{16, 17, 18, 19, 20},
A1D{21, 22, 23, 24, 25} };
for (int i = LoBound; i <= HiBound; ++i) {
for (int j = LoBound; j <= HiBound; ++j) {
std::cout << arr[-i][-j] << " ";
}
std::cout << "\n";
}
return 0;
}