RAUL  0.8.0
Array.hpp
1 /* This file is part of Raul.
2  * Copyright (C) 2007-2009 David 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 <cstddef>
23 #include <algorithm>
24 #include "Deletable.hpp"
25 
26 namespace Raul {
27 
28 
36 template <class T>
37 class Array : public Deletable
38 {
39 public:
40  explicit Array(size_t size = 0) : _size(size), _elems(NULL) {
41  if (size > 0)
42  _elems = new T[size];
43  }
44 
45  Array(size_t size, T initial_value) : _size(size), _elems(NULL) {
46  if (size > 0) {
47  _elems = new T[size];
48  for (size_t i = 0; i < size; ++i)
49  _elems[i] = initial_value;
50  }
51  }
52 
53  Array(size_t size, const Array<T>& contents) : _size(size) {
54  assert(contents.size() >= size);
55  _elems = new T[size];
56  for (size_t i = 0; i < std::min(size, contents.size()); ++i)
57  _elems[i] = contents[i];
58  }
59 
60  Array(size_t size, const Array<T>& contents, T initial_value=T()) : _size(size) {
61  _elems = new T[size];
62  const size_t end = std::min(size, contents.size());
63  for (size_t i = 0; i < end; ++i)
64  _elems[i] = contents[i];
65  for (size_t i = end; i < size; ++i)
66  _elems[i] = initial_value;
67  }
68 
69  ~Array() {
70  delete[] _elems;
71  }
72 
73  virtual void alloc(size_t num_elems) {
74  assert(num_elems > 0);
75 
76  delete[] _elems;
77  _size = num_elems;
78 
79  _elems = new T[num_elems];
80  }
81 
82  virtual void alloc(size_t num_elems, T initial_value) {
83  assert(num_elems > 0);
84 
85  delete[] _elems;
86  _size = num_elems;
87 
88  _elems = new T[num_elems];
89  for (size_t i = 0; i < _size; ++i)
90  _elems[i] = initial_value;
91  }
92 
93  inline size_t size() const { return _size; }
94 
95  inline T& operator[](size_t i) const { assert(i < _size); return _elems[i]; }
96 
97  inline T& at(size_t i) const { assert(i < _size); return _elems[i]; }
98 
99 private:
100  size_t _size;
101  T* _elems;
102 };
103 
104 
105 } // namespace Raul
106 
107 #endif // RAUL_ARRAY_HPP
Something with a virtual destructor.
Definition: Deletable.hpp:28
Definition: Array.hpp:26
An array.
Definition: Array.hpp:37