-
Vector bounds check
How would you write a Vector template class that checks the indexes passed to the [] operator to make sure they are correct....
Inheritance??
I have this so far
Code:
template <class T> class Vector
{
public:
Vector();
Vector(int size_t n);
~Vector();
std::vector<int> array;
try{
array.at(1000) = 0;
}
catch(std::out_of_range o){
std::cout<<o.what()<<std::endl;
}
-
Not sure I understand. Are you trying to derive a vector sub-class that provides bounds checking?
If so, vector::at() already does bounds checking. It throws a std::out_of_range exception if the value is not in the range.
Thus you use [] when you want the speed of an array, and at() when you don't want to hurt yourself (especially with calculated or arguement values which could be invalid).
-
Yes thats what i'm trying to do...derive a template vector sub-class that provides bound checking
-
In your child class, provide an at() function or redefine operator[] such that you do something special (throw an exception, for example) when the inputted index is equal to or greater than size().