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
|
#include <iostream>
#include <initializer_list>
template <typename T>
void print(const T *a, size_t d, size_t *sz, size_t *strides) {
if (d == 1)
for (size_t i = 0; i < *sz; i++)
std::cout << a[i] << ' ';
else
for (size_t i = 0; i < *sz; i++)
print(a + i * *strides, d - 1, sz + 1, strides + 1);
std::cout << '\n';
}
template <typename T>
void fill(T *a, size_t d, size_t *sz, size_t *strides,
T first, T last, T &ch) {
if (d == 1)
for (size_t i = 0; i < *sz; i++) {
a[i] = ch++;
if (ch > last)
ch = first;
}
else
for (size_t i = 0; i < *sz; i++)
fill(a + i * *strides, d - 1, sz + 1, strides + 1,
first, last, ch);
}
template <typename T>
class MultiArray {
T *data;
size_t nDims;
size_t *sizes;
size_t *strides;
public:
MultiArray(std::initializer_list<int> sz) {
nDims = sz.size();
sizes = new size_t[nDims];
size_t i = 0;
for (auto x: sz)
sizes[i++] = x;
strides = new size_t[nDims];
strides[nDims - 1] = sizes[nDims - 1];
for (size_t i = nDims - 1; i-- > 0; )
strides[i] = strides[i + 1] * sizes[i];
data = new T[strides[0]];
}
~MultiArray() {
delete [] data;
delete [] strides;
delete [] sizes;
}
void fill(T first, T last);
void print();
};
template <typename T>
void MultiArray<T>::print() {
::print(data, nDims, sizes, strides + 1);
}
template <typename T>
void MultiArray<T>::fill(T first, T last) {
T ch = first;
::fill(data, nDims, sizes, strides + 1, first, last, ch);
}
int main() {
MultiArray<char> ma({2,3,4,5});
ma.fill('A', 'Z');
ma.print();
MultiArray<int> ma2({3,2,4});
ma2.fill(0, 9);
ma2.print();
}
|