RAUL  0.5.1
Array.hpp
1 /* This file is part of Raul.
2  * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
3  *
4  * Raul is free software; you can redistribute it and/or modify it under the
5  * terms of the GNU General Public License as published by the Free Software
6  * Foundation; either version 2 of the License, or (at your option) any later
7  * version.
8  *
9  * Raul is distributed in the hope that it will be useful, but WITHOUT ANY
10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
16  */
17 
18 #ifndef RAUL_ARRAY_HPP
19 #define RAUL_ARRAY_HPP
20 
21 #include <cassert>
22 #include <cstdlib>
23 #include "types.hpp"
24 #include "Deletable.hpp"
25 
26 namespace Raul {
27 
28 
35 template <class T>
36 class Array : public Deletable
37 {
38 public:
39  Array(size_t size = 0) : _size(size), _top(0), _elems(NULL) {
40  if (size > 0)
41  _elems = new T[size];
42  }
43 
44  Array(size_t size, T initial_value) : _size(size), _top(0), _elems(NULL) {
45  if (size > 0) {
46  _elems = new T[size];
47  for (size_t i=0; i < size; ++i)
48  _elems[i] = initial_value;
49  }
50  }
51 
52  Array(size_t size, const Array<T>& contents) : _size(size), _top(size+1) {
53  _elems = new T[size];
54  if (size <= contents.size())
55  memcpy(_elems, contents._elems, size * sizeof(T));
56  else
57  memcpy(_elems, contents._elems, contents.size() * sizeof(T));
58  }
59 
60  ~Array() {
61  delete[] _elems;
62  }
63 
64  void alloc(size_t num_elems) {
65  assert(num_elems > 0);
66 
67  delete[] _elems;
68  _size = num_elems;
69  _top = 0;
70 
71  _elems = new T[num_elems];
72  }
73 
74  void alloc(size_t num_elems, T initial_value) {
75  assert(num_elems > 0);
76 
77  delete[] _elems;
78  _size = num_elems;
79  _top = 0;
80 
81  _elems = new T[num_elems];
82  for (size_t i=0; i < _size; ++i)
83  _elems[i] = initial_value;
84  }
85 
86  void push_back(T n) {
87  assert(_top < _size);
88  _elems[_top++] = n;
89  }
90 
91  inline size_t size() const { return _size; }
92 
93  inline T& operator[](size_t i) const { assert(i < _size); return _elems[i]; }
94 
95  inline T& at(size_t i) const { assert(i < _size); return _elems[i]; }
96 
97 private:
98  size_t _size;
99  size_t _top; // points to empty element above "top" element
100  T* _elems;
101 };
102 
103 
104 } // namespace Raul
105 
106 #endif // RAUL_ARRAY_HPP
Something with a virtual destructor.
Definition: Deletable.hpp:28
An array.
Definition: Array.hpp:36