I tried to index a vector
using a negative index. The vector::at()
member function checks whether the specified index is within the bounds of the vector, and if this does not occur, an out_of_range
exception is thrown.
vector<float> array; // sample vector
array.push_back(0.123);
array.push_back(1.234);
array.push_back(2.345);
array.push_back(3.456);
array.push_back(4.567);
int index = -1;
float f = array.at(index);
cout << f << endl;
The signature of vector::at()
member function requires that the specified parameter is of vector<T>::size_type
type, and this type is unsigned int
for the vector, so the compiler should perform an implicit conversion from int
(the type of the index
variable) to unsigned int
. Since the index
value is -1
in the above example, the implicitly converted index
is 4294967295
(that is the max value of the unsigned int
type): this value is passed to vector::at()
member function, which throws an out_of_range
exception.
In other words, this exception is not thrown because the vector::at()
member function sees that the index
is less than zero, but rather because the implicitly converted index
is greater than the current size of the vector
. Is this a correct explanation?