00001 /* 00002 Copyright (c) 2010 Les Newell. All rights reserved 00003 00004 This program is free software: you can redistribute it and/or modify 00005 it under the terms of the GNU General Public License as published by 00006 the Free Software Foundation, either version 3 of the License, or 00007 (at your option) any later version. 00008 00009 This program is distributed in the hope that it will be useful, 00010 but WITHOUT ANY WARRANTY; without even the implied warranty of 00011 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00012 GNU General Public License for more details. 00013 00014 You should have received a copy of the GNU General Public License 00015 along with this program. If not, see <http://www.gnu.org/licenses/>. 00016 */ 00017 00018 #ifndef ARRAY_H_INCLUDED 00019 #define ARRAY_H_INCLUDED 00020 00021 #define GROWAHEAD 5 00022 00023 template <class T> 00024 class GrowArray 00025 { 00026 00027 public: 00028 GrowArray() 00029 { 00030 m_count=0; 00031 m_size = 0; 00032 m_data = NULL; 00033 }; 00034 00035 ~GrowArray() 00036 { 00037 Clear(); 00038 }; 00039 00040 00041 void Add(const T& data) 00042 { 00043 if (m_count >= m_size) 00044 Grow(GROWAHEAD); 00045 m_data[m_count] = data; 00046 m_count ++; 00047 }; 00048 00049 00050 int Index(const T& data) 00051 { 00052 for (int ct=0; ct < m_count; ct++) 00053 { 00054 if (data == m_data[ct]) 00055 return(ct); 00056 } 00057 return(-1); 00058 } 00059 00060 inline T& operator[](const int index) const 00061 { 00062 return(m_data[index]); 00063 }; 00064 00065 void Swap(const int i1,const int i2) 00066 { 00067 if ((unsigned int)i1 >= (unsigned int)m_count) 00068 return; 00069 if ((unsigned int)i2 >= (unsigned int)m_count) 00070 return; 00071 T tmp = m_data[i1]; 00072 m_data[i1] = m_data[i2]; 00073 m_data[i2] = tmp; 00074 } 00075 00076 void Remove(const int index) 00077 { 00078 if ((unsigned int)index >= (unsigned int)m_count) 00079 return; 00080 for (int ct=index; ct<m_count -1; ct++) 00081 m_data[ct] = m_data[ct+1]; 00082 m_count --; 00083 }; 00084 00085 void Clear(void) 00086 { 00087 m_count=0; 00088 free(m_data); 00089 m_size=0; 00090 m_data = NULL; 00091 }; 00092 00093 void Empty(void) 00094 { 00095 m_count=0; 00096 }; 00097 00098 void Grow(size_t amount) 00099 { 00100 m_size += amount; 00101 m_data = (T*) realloc (m_data, sizeof(T) * m_size); 00102 } 00103 00104 inline int GetCount(void) const 00105 { 00106 return(m_count); 00107 } 00108 00109 T* m_data; //slighty ugly to expose this but it is faster 00110 00111 00112 protected: 00113 int m_size; 00114 int m_count; 00115 }; 00116 00117 00118 00119 #endif 00120
1.7.0