| 1 | ///////////////////////////////////////////////////////////////// |
|---|
| 2 | // SafeVector.h |
|---|
| 3 | // |
|---|
| 4 | // STL vector with array bounds checking. To enable bounds |
|---|
| 5 | // checking, #define ENABLE_CHECKS. |
|---|
| 6 | ///////////////////////////////////////////////////////////////// |
|---|
| 7 | |
|---|
| 8 | #ifndef SAFEVECTOR_H |
|---|
| 9 | #define SAFEVECTOR_H |
|---|
| 10 | |
|---|
| 11 | #include <cassert> |
|---|
| 12 | #include <vector> |
|---|
| 13 | #include <cstring> |
|---|
| 14 | |
|---|
| 15 | ///////////////////////////////////////////////////////////////// |
|---|
| 16 | // SafeVector |
|---|
| 17 | // |
|---|
| 18 | // Class derived from the STL std::vector for bounds checking. |
|---|
| 19 | ///////////////////////////////////////////////////////////////// |
|---|
| 20 | |
|---|
| 21 | template<class TYPE> |
|---|
| 22 | class SafeVector : public std::vector<TYPE>{ |
|---|
| 23 | public: |
|---|
| 24 | |
|---|
| 25 | // miscellaneous constructors |
|---|
| 26 | SafeVector() : std::vector<TYPE>() {} |
|---|
| 27 | SafeVector (size_t size) : std::vector<TYPE>(size) {} |
|---|
| 28 | SafeVector (size_t size, const TYPE &value) : std::vector<TYPE>(size, value) {} |
|---|
| 29 | SafeVector (const SafeVector &source) : std::vector<TYPE>(source) {} |
|---|
| 30 | |
|---|
| 31 | #ifdef ENABLE_CHECKS |
|---|
| 32 | |
|---|
| 33 | // [] array bounds checking |
|---|
| 34 | TYPE &operator[](int index){ |
|---|
| 35 | assert (index >= 0 && index < (int) size()); |
|---|
| 36 | return std::vector<TYPE>::operator[] ((size_t) index); |
|---|
| 37 | } |
|---|
| 38 | |
|---|
| 39 | // [] const array bounds checking |
|---|
| 40 | const TYPE &operator[] (int index) const { |
|---|
| 41 | assert (index >= 0 && index < (int) size()); |
|---|
| 42 | return std::vector<TYPE>::operator[] ((size_t) index) ; |
|---|
| 43 | } |
|---|
| 44 | |
|---|
| 45 | #endif |
|---|
| 46 | |
|---|
| 47 | }; |
|---|
| 48 | |
|---|
| 49 | // some commonly used vector types |
|---|
| 50 | typedef SafeVector<int> VI; |
|---|
| 51 | typedef SafeVector<VI> VVI; |
|---|
| 52 | typedef SafeVector<VVI> VVVI; |
|---|
| 53 | typedef SafeVector<float> VF; |
|---|
| 54 | typedef SafeVector<VF> VVF; |
|---|
| 55 | typedef SafeVector<VVF> VVVF; |
|---|
| 56 | |
|---|
| 57 | #endif |
|---|