Biff wrote:
Is there a common way to check for vector indexes being in bounds?
You could use member function
reference
at(size_type __n) { _M_range_check( __n);
return (*this)[__n]; }
const_reference
at(size_type __n) const { _M_range_check( __n);
return (*this)[__n]; }
but that throws an exception and is *not* appropriate
if you are trying to trap programming errors (bugs).
My version of the STL has no such check, even in debug builds.
I was considering deriving a class from Vector with its own operator[]
and using that in my code instead of std::vector.
Then I'd use an #ifdef _DEBUG switch
which typedef'ed my vector class name to std::vector
if in release or used the derived class if in debug.
Does that sound reasonable?
It sounds very reasonable.
Is there an easier and more common way?
My GNU C++ compiler defines members:
reference
operator[](size_type __n) { return *(begin() + __n); }
const_reference
operator[](size_type __n) const { return *(begin() + __n); }
in /usr/include/c++/3.4.0/bits/stl_vector.h
You could redefine them:
reference
operator[](size_type __n) {
assert(__n < this->size()); return *(begin() + __n); }
const_reference
operator[](size_type __n) const {
assert(__n < this->size()); return *(begin() + __n); }
Anyway, you should check your implementation.
You might find that this has already been done for you.