Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float Values as an index in an Array in C++

Tags:

c++

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?

like image 438
Venus Avatar asked Feb 22 '10 12:02

Venus


People also ask

Can an array index be a float C?

Yes. But it's pointless. The float value will be truncated to an integer.

Can we use float value in indexing?

Floats cannot be used as indices.

How do you store float values in an array?

fill(float[] a, float val) method assigns the specified float value to each element of the specified array of floats.

Can you index a float?

Any float or real expression is considered imprecise and cannot be a key of an index; a float or real expression can be used in an indexed view but not as a key.


2 Answers

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]
like image 98
alemjerus Avatar answered Oct 11 '22 13:10

alemjerus


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.)

like image 38
kennytm Avatar answered Oct 11 '22 13:10

kennytm