RAUL 0.7.0
|
00001 /* This file is part of Raul. 00002 * Copyright (C) 2007-2009 David Robillard <http://drobilla.net> 00003 * 00004 * Raul is free software; you can redistribute it and/or modify it under the 00005 * terms of the GNU General Public License as published by the Free Software 00006 * Foundation; either version 2 of the License, or (at your option) any later 00007 * version. 00008 * 00009 * Raul is distributed in the hope that it will be useful, but WITHOUT ANY 00010 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 00011 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details. 00012 * 00013 * You should have received a copy of the GNU General Public License along 00014 * with this program; if not, write to the Free Software Foundation, Inc., 00015 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 00016 */ 00017 00018 #ifndef RAUL_ARRAY_HPP 00019 #define RAUL_ARRAY_HPP 00020 00021 #include <cassert> 00022 #include <cstddef> 00023 #include <algorithm> 00024 #include "Deletable.hpp" 00025 00026 namespace Raul { 00027 00028 00035 template <class T> 00036 class Array : public Deletable 00037 { 00038 public: 00039 Array(size_t size = 0) : _size(size), _elems(NULL) { 00040 if (size > 0) 00041 _elems = new T[size]; 00042 } 00043 00044 Array(size_t size, T initial_value) : _size(size), _elems(NULL) { 00045 if (size > 0) { 00046 _elems = new T[size]; 00047 for (size_t i = 0; i < size; ++i) 00048 _elems[i] = initial_value; 00049 } 00050 } 00051 00052 Array(size_t size, const Array<T>& contents) : _size(size) { 00053 assert(contents.size() >= size); 00054 _elems = new T[size]; 00055 for (size_t i = 0; i < std::min(size, contents.size()); ++i) 00056 _elems[i] = contents[i]; 00057 } 00058 00059 Array(size_t size, const Array<T>& contents, T initial_value=T()) : _size(size) { 00060 _elems = new T[size]; 00061 const size_t end = std::min(size, contents.size()); 00062 for (size_t i = 0; i < end; ++i) 00063 _elems[i] = contents[i]; 00064 for (size_t i = end; i < size; ++i) 00065 _elems[i] = initial_value; 00066 } 00067 00068 ~Array() { 00069 delete[] _elems; 00070 } 00071 00072 virtual void alloc(size_t num_elems) { 00073 assert(num_elems > 0); 00074 00075 delete[] _elems; 00076 _size = num_elems; 00077 00078 _elems = new T[num_elems]; 00079 } 00080 00081 virtual void alloc(size_t num_elems, T initial_value) { 00082 assert(num_elems > 0); 00083 00084 delete[] _elems; 00085 _size = num_elems; 00086 00087 _elems = new T[num_elems]; 00088 for (size_t i = 0; i < _size; ++i) 00089 _elems[i] = initial_value; 00090 } 00091 00092 inline size_t size() const { return _size; } 00093 00094 inline T& operator[](size_t i) const { assert(i < _size); return _elems[i]; } 00095 00096 inline T& at(size_t i) const { assert(i < _size); return _elems[i]; } 00097 00098 private: 00099 size_t _size; 00100 T* _elems; 00101 }; 00102 00103 00104 } // namespace Raul 00105 00106 #endif // RAUL_ARRAY_HPP