Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Fastest check array bounds

Tags:

c++

arrays

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?

like image 871
DividedByZero Avatar asked Sep 26 '12 16:09

DividedByZero


2 Answers

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.

like image 44
Sergey Kalinichenko Avatar answered Oct 20 '22 12:10

Sergey Kalinichenko


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];
}
like image 123
Lyubomir Vasilev Avatar answered Oct 20 '22 11:10

Lyubomir Vasilev