RAUL  0.8.0
ArrayStack.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_ARRAYSTACK_HPP
19 #define RAUL_ARRAYSTACK_HPP
20 
21 #include <algorithm>
22 #include <cassert>
23 #include <cstddef>
24 
25 #include "raul/Array.hpp"
26 #include "raul/Deletable.hpp"
27 
28 namespace Raul {
29 
30 
34 template <class T>
35 class ArrayStack : public Array<T>
36 {
37 public:
38  explicit ArrayStack(size_t size = 0) : Array<T>(size), _top(0) {}
39 
40  ArrayStack(size_t size, T initial_value) : Array<T>(size, initial_value), _top(0) {}
41 
42  ArrayStack(size_t size, const Array<T>& contents) : Array<T>(size, contents), _top(size + 1) {}
43 
44  ~Array() {
45  delete[] _elems;
46  }
47 
48  void alloc(size_t num_elems) {
49  Array<T>::alloc(num_elems);
50  _top = 0;
51  }
52 
53  void alloc(size_t num_elems, T initial_value) {
54  Array<T>::alloc(num_elems, initial_value);
55  _top = 0;
56  }
57 
58  void push_back(T n) {
59  assert(_top < _size);
60  _elems[_top++] = n;
61  }
62 
63  inline size_t size() const { return _size; }
64 
65  inline T& operator[](size_t i) const { assert(i < _size); return _elems[i]; }
66 
67  inline T& at(size_t i) const { assert(i < _size); return _elems[i]; }
68 
69 private:
70  size_t _top; // Index of empty element following the top element
71 };
72 
73 
74 } // namespace Raul
75 
76 #endif // RAUL_ARRAY_HPP
Definition: Array.hpp:26
An array that can also be used as a stack (with a fixed maximum size).
Definition: ArrayStack.hpp:35
An array.
Definition: Array.hpp:37