ReusableVector.h
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include <vector>
00021 #include <stdexcept>
00022
00023 #ifndef __REUSABLE_VECTOR_H__
00024 #define __REUSABLE_VECTOR_H__
00025
00026
00027
00028
00029 template <class DATA_TYPE>
00030 class ReusableVector
00031 {
00032 public:
00033 ReusableVector(): myCont(), myNextEmpty(0) {}
00034 virtual ~ReusableVector();
00035
00036
00037 void reset();
00038
00039 void clear() {reset();}
00040
00041
00042
00043 DATA_TYPE& getNextEmpty();
00044
00045
00046
00047 DATA_TYPE& get(unsigned int index);
00048
00049
00050
00051 int size() const {return(myNextEmpty);}
00052
00053 void rmLast();
00054
00055 protected:
00056 std::vector<DATA_TYPE*> myCont;
00057 unsigned int myNextEmpty;
00058 private:
00059 ReusableVector& operator=(const ReusableVector& rv);
00060 ReusableVector(const ReusableVector& rv);
00061 };
00062
00063
00064
00065
00066 template <class DATA_TYPE>
00067 ReusableVector<DATA_TYPE>::~ReusableVector()
00068 {
00069 for(unsigned int i = 0; i < myCont.size(); i++)
00070 {
00071
00072 delete myCont[i];
00073 myCont[i] = NULL;
00074 }
00075 myCont.clear();
00076 myNextEmpty = 0;
00077 }
00078
00079
00080 template <class DATA_TYPE>
00081 void ReusableVector<DATA_TYPE>::reset()
00082 {
00083
00084
00085 myNextEmpty = 0;
00086 }
00087
00088
00089 template <class DATA_TYPE>
00090 DATA_TYPE& ReusableVector<DATA_TYPE>::getNextEmpty()
00091 {
00092 if(myNextEmpty == myCont.size())
00093 {
00094
00095 myCont.resize(myCont.size() + 1);
00096
00097
00098 myCont[myNextEmpty] = new DATA_TYPE;
00099 }
00100 else
00101 {
00102
00103
00104 myCont[myNextEmpty]->clear();
00105 }
00106
00107 DATA_TYPE* returnVal = myCont[myNextEmpty];
00108
00109
00110 ++myNextEmpty;
00111
00112 return(*returnVal);
00113 }
00114
00115
00116 template <class DATA_TYPE>
00117 DATA_TYPE& ReusableVector<DATA_TYPE>::get(unsigned int index)
00118 {
00119 if((index < myNextEmpty) && (index >= 0))
00120 {
00121
00122 if(myCont[index] == NULL)
00123 {
00124 throw(std::runtime_error("ReusableVector::get BUG, found a null pointer."));
00125 }
00126 return(*myCont[index]);
00127 }
00128
00129
00130 throw(std::runtime_error("ReusableVector::get called with out of range index."));
00131
00132 }
00133
00134 template <class DATA_TYPE>
00135 void ReusableVector<DATA_TYPE>::rmLast()
00136 {
00137 if(myNextEmpty > 0)
00138 {
00139 --myNextEmpty;
00140 }
00141 }
00142
00143 #endif