C ++ - the fastest bounds of a validation array

I need a very fast way to check the boundaries of an array. My current limitations are:

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];
    }
}

Is there a faster way to check if an index is specified from the boundaries of an array?

EDIT:

My solution creates problems with negative indices. Is there any way to fix this?

+5
source share
4 answers

Your check skips negative values: if the size 5, and the index -1, the result of integer division is zero, but the index is clearly out of range.

You can fix this problem by setting the indexunsigned parameter . Type sizemust be size_t.

+2
source

, - , .

, :

index >= size

, , , index 0, unsigned size_t size index, .

:

T &operator[](size_t index) {
    if (index >= size)
        throw OUT_OF_RANGE; //#define OUT_OF_RANGE 0x0A
    return array[index];
}
+5

Yes, do not use division, because division is slow (plus it fails if size == 0). Plain

if(index >= size || index < 0)

will be wonderful.

+3
source

The fastest way to check the bounds of an array is not to check. Subscribers operator[]should be responsible for ensuring that they know what they are doing and not call it a bad index.

+1
source

All Articles