blob: 9922265299ae188379db52ca7699107d93914b7d [file] [log] [blame]
Éanna Ó Catháinc6ab02a2021-04-07 14:35:25 +01001//
2// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5#pragma once
6
7#include <stdio.h>
8#include <iterator>
9
10/**
11 * Class Array2d is a data structure that represents a two dimensional array.
12 * The data is allocated in contiguous memory, arranged row-wise
13 * and individual elements can be accessed with the () operator.
14 * For example a two dimensional array D of size (M, N) can be accessed:
15 *
16 * _|<------------- col size = N -------->|
17 * | D(r=0, c=0) D(r=0, c=1)... D(r=0, c=N)
18 * | D(r=1, c=0) D(r=1, c=1)... D(r=1, c=N)
19 * | ...
20 * row size = M ...
21 * | ...
22 * _ D(r=M, c=0) D(r=M, c=1)... D(r=M, c=N)
23 *
24 */
25template<typename T>
26class Array2d
27{
28private:
29 size_t m_rows;
30 size_t m_cols;
31 T* m_data;
32
33public:
34 /**
35 * Creates the array2d with the given sizes.
36 *
37 * @param rows number of rows.
38 * @param cols number of columns.
39 */
40 Array2d(unsigned rows, unsigned cols)
41 {
42 if (rows == 0 || cols == 0) {
43 printf("Array2d constructor has 0 size.\n");
44 m_data = nullptr;
45 return;
46 }
47 m_rows = rows;
48 m_cols = cols;
49 m_data = new T[rows * cols];
50 }
51
52 ~Array2d()
53 {
54 delete[] m_data;
55 }
56
57 T& operator() (unsigned int row, unsigned int col)
58 {
59 return m_data[m_cols * row + col];
60 }
61
62 T operator() (unsigned int row, unsigned int col) const
63 {
64 return m_data[m_cols * row + col];
65 }
66
67 /**
68 * Gets rows number of the current array2d.
69 * @return number of rows.
70 */
71 size_t size(size_t dim)
72 {
73 switch (dim)
74 {
75 case 0:
76 return m_rows;
77 case 1:
78 return m_cols;
79 default:
80 return 0;
81 }
82 }
83
84 /**
85 * Gets the array2d total size.
86 */
87 size_t totalSize()
88 {
89 return m_rows * m_cols;
90 }
91
92 /**
93 * array2d iterator.
94 */
95 using iterator=T*;
96 using const_iterator=T const*;
97
98 iterator begin() { return m_data; }
99 iterator end() { return m_data + totalSize(); }
100 const_iterator begin() const { return m_data; }
101 const_iterator end() const { return m_data + totalSize(); };
102};