trajopt
 All Classes Namespaces Files Functions Variables Typedefs Pages
basic_array.hpp
1 #pragma once
2 #include <vector>
3 
4 namespace util {
5 
6 template<class T>
7 struct BasicArray {
8 
9  int m_nRow;
10  int m_nCol;
11  std::vector<T> m_data;
12 
13  BasicArray() :
14  m_nRow(0), m_nCol(0) {
15  }
16  BasicArray(int nRow, int nCol) :
17  m_nRow(nRow), m_nCol(nCol) {
18  m_data.resize(m_nRow * m_nCol);
19  }
20  BasicArray(int nRow, int nCol, const T* data) :
21  m_nRow(nRow), m_nCol(nCol), m_data(data, data+nRow*nCol) {
22  }
23  BasicArray(const BasicArray& x) :
24  m_nRow(x.m_nRow), m_nCol(x.m_nCol), m_data(x.m_data) {
25  }
26  void resize(int nRow, int nCol) {
27  m_nRow = nRow;
28  m_nCol = nCol;
29  m_data.resize(m_nRow * m_nCol);
30  }
31 
32  int rows() const {
33  return m_nRow;
34  }
35  int cols() const {
36  return m_nCol;
37  }
38  int size() const {
39  return m_data.size();
40  }
41  BasicArray block(int startRow, int startCol, int nRow, int nCol) const {
42  BasicArray out;
43  out.resize(nRow, nCol);
44  for (int iRow = 0; iRow < nRow; ++iRow) {
45  for (int iCol = 0; iCol < nCol; ++iCol) {
46  out(iRow, iCol) = at(iRow + startRow, iCol + startCol);
47  }
48  }
49  return out;
50  }
51  std::vector<T> rblock(int startRow, int startCol, int nCol) const {
52  std::vector<T> out(nCol);
53  for (int iCol = 0; iCol < nCol; ++iCol) {
54  out[iCol] = at(startRow, iCol + startCol);
55  }
56  return out;
57  }
58  BasicArray middleRows(int start, int n) {
59  BasicArray out;
60  out.resize(n, m_nCol);
61  for (int i = start; i < start + n; ++i) {
62  for (int j = 0; j < m_nCol; ++j) {
63  out(i, j) = at(i, j);
64  }
65  }
66  return out;
67  }
68  BasicArray topRows(int n) {
69  return middleRows(0, n);
70  }
71  BasicArray bottomRows(int n) {
72  return middleRows(m_nRow - n, n);
73  }
74 
75  const T& at(int row, int col) const {
76  return m_data.at(row * m_nCol + col);
77  }
78  T& at(int row, int col) {
79  return m_data.at(row * m_nCol + col);
80  }
81  const T& operator()(int row, int col) const {
82  return m_data.at(row * m_nCol + col);
83  }
84  T& operator()(int row, int col) {
85  return m_data.at(row * m_nCol + col);
86  }
87 
88  std::vector<T> col(int col) {
89  std::vector<T> out;
90  out.reserve(m_nRow);
91  for (int row = 0; row < m_nRow; row++)
92  out.push_back(at(row, col));
93  return out;
94  }
95 
96  std::vector<T> row(int row) {
97  std::vector<T> out;
98  out.reserve(m_nCol);
99  for (int col = 0; col < m_nCol; col++)
100  out.push_back(at(row, col));
101  return out;
102  }
103 
104  std::vector<T> flatten() {
105  return m_data;
106  }
107 
108  T* data() {
109  return m_data.data();
110  }
111  T* data() const {
112  return m_data.data();
113  }
114 
115 };
116 
117 }