debugcppModerate
Fixed array with configurable bounds
Viewed 0 times
configurablewitharrayfixedbounds
Problem
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
Now I'm curious about what could be done to make this Array more mature. Say, like a Boost component.
[-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
#include
#include
template 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 initList)
{
std::copy(initList.begin(), initList.end(), arr_);
}
T& operator[](int ix)
{
assert(ix >= LoBound && ix = LoBound && ix ;
Array 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;
}Solution
It looks pretty clean to me.
-
The copy constructor doesn't have to be explicitly declared, you could
-
You shouldn't
-
Actually, maybe could provide an explicit constructor that takes a fill value. That can be handy.
-
A
-
Mark the class
-
If you're interested in making this class Standard compliant, well, there's a long road ahead
-
The copy constructor doesn't have to be explicitly declared, you could
= default it or just omit.-
You shouldn't
fill() the array. It is already default constructed, so that's just duplicated work. The default constructor again could be = default or omitted. -
Actually, maybe could provide an explicit constructor that takes a fill value. That can be handy.
-
A
size() method to return sizeof(arr_) / sizeof(arr_[0]) should be useful, for both internal and external uses.-
Mark the class
final? I'd probably do it, but that's probably a matter of personal preference.-
If you're interested in making this class Standard compliant, well, there's a long road ahead
;). It needs iterators and several other methods ([c]begin/[c]end/front/back/at...). Look into std::array for the details.Context
StackExchange Code Review Q#113861, answer score: 11
Revisions (0)
No revisions yet.