索引具有负索引的std :: vector [英] Indexing an std::vector with a negative index
问题描述
我尝试使用负索引来索引向量
。 vector :: at()
成员函数检查指定的索引是否在向量的边界内,如果没有发生,则 out_of_range
抛出异常。
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;
的签名vector :: at()
成员函数要求指定的参数为向量< T> :: size_type
类型,并且此类型为 unsigned int
用于向量,因此编译器应该执行从 int
( index
变量的类型)到 unsigned int
。由于在上面的例子中 index
的值是 -1
,隐式转换的 code>是
4294967295
(即 unsigned int
类型的最大值):此值传递到 vector :: at()
成员函数,它引发一个 out_of_range
异常。
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.
换句话说,这个异常不会抛出,因为 vector :: at()
成员函数看到 / code>小于零,而是因为隐式转换的
index
大于向量的当前大小
。这是正确的解释吗?
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?
推荐答案
是的,这是一个正确的解释。 (除了在处接受一个
std :: size_t
,这是一些未指定的无符号整数类型(通常是位宽您的系统上的指针),它允许您的系统上 unsigned int
,但不是标准强制的。)
Yes, that is a correct explation. (Except at
takes a 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.)
另外,请注意无符号到有符号的转换:标准不要求它是一个往返签名 - >无符号 - >负值,一些编译器积极地优化意想不到的方式。
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.
这篇关于索引具有负索引的std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!