Float Values as an index in an Array in C++
Can a float value be开发者_如何学C used as the index of an array? What will happen if an expression used as an index resulted to a float value?
The float value will be casted to int (it can give warning or error depending on compiler's warning level)
s1 = q[12.2]; // same as q[12]
s2 = q[12.999999]; // same as q[12]
s3 = q[12.1/6.2]; // same as q[1]
Yes. But it's pointless. The float value will be truncated to an integer.
(You can use std::map<float, T>
, however, but most of the time you'll miss the intended values because of inaccuracy.)
A C++ array is a contiguous sequence of memory locations. a[x]
means "the xth memory location after one pointed to by a
."
What would it mean to access the 12.4th object in a sequence?
It will be casted to int.
This is an error. In [expr.sub]
:
A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type.
I am not aware of a clause in the standard that specifies that conversion should happen here (admittedly, I would not be surprised if such a clause existed), although testing with ideone.com did produce a compilation error.
However, if you're subscripting a class rather than a pointer — e.g. std::vector
or std::array
— then the overload of operator[]
will have the usual semantics of a function call, and floating-point arguments will get converted to the corresponding size_type
.
精彩评论