I need a very fast way to check bounds of an array.
My current check bounds is:
template<typename T>
class SmartArray {
//...
int size;
T* array;
T &operator[](int index) {
if (index/size!=0)
throw OUT_OF_RANGE; //#define OUT_OF_RANGE 0x0A
return array[index];
}
}
There is faster way to check if index is out of array bounds?
EDIT:
My solution is making troubles with negative indexes.
There is a way to fix this?
Your check misses negative values: if the size is
5and the index is-1, the result of the integer division is zero, but the index is clearly out of range.You can fix this issue by making the
indexparameter unsigned. The type ofsizeshould besize_tas well.