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 5
and 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 index
parameter unsigned. The type of size
should be size_t
as well.
Generally speaking, division is a slow operation, so I would avoid that.
I think a simple comparison will be more efficient:
index >= size
This would, however, miss the case where index
is less than 0 but if you use unsigned
or size_t
for the size
and index
variables, that would not be a problem.
So it becomes:
T &operator[](size_t index) {
if (index >= size)
throw OUT_OF_RANGE; //#define OUT_OF_RANGE 0x0A
return array[index];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With