Can a float value be used as the index of an array? What will happen if an expression used as an index resulted to a float value?
+7
A:
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]
alemjerus
2010-02-22 12:39:14
+6
A:
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.)
KennyTM
2010-02-22 12:39:21
+1 for `std::map`
Prasoon Saurav
2010-02-22 12:48:35
As for inaccuracy, I think there should be some way to provide your own compare function where you can include an 'epsilon'... a tolerance of sorts.
Vulcan Eager
2010-02-23 10:18:16
@Agnel Kurian std::map of course allows you to exactly this
anon
2010-02-23 10:21:21
+1
A:
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?
Crashworks
2010-02-23 10:16:45
Note to pedants: yes, I know array offsets are not a simple addition of integers to pointers: this sentence assumes that a "memory location" is the size of an array member, so for an int a[], a[5] means the fifth word, not the fifth byte.
Crashworks
2010-02-23 10:21:35