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?
Yes, that is a correct explanation. (Except at
takes a vector::size_type
, usually std::size_t
, which is some unspecified unsigned integer type (usually the bit-width of pointers on your system). It being unsigned int
on your system is allowed, but not mandated by the standard; 32 bit unsigned int
with 64 bit size_t
is common.)
As an aside, be careful with unsigned to signed conversion: the standard does not require it be a round-trip going signed->unsigned->signed for negative values, and some compilers aggressively optimize in unexpected ways.