Junior — Middle
Is it recommended to use float type as a key in data structures?
sobes.tech AI
Answer from AI
Using the float type as a key in data structures (such as hash tables or dictionaries) is not recommended. The main reason is the characteristics of floating-point number representation: they can have inaccuracies during arithmetic operations and comparisons, leading to unexpected results when searching or inserting.
For example, two numeric values that are logically equal may differ by a very small amount due to rounding errors, and then the keys will be perceived as different.
If it is necessary to use a floating-point numeric key, it is better to:
- Use integer keys, for example, by scaling the number (multiplying by 1000 and converting to
int), if possible. - Use a string representation of the number with fixed precision.
- Implement a custom comparator considering an acceptable error margin.
Example of a problem:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<float, std::string> map;
float a = 0.1f + 0.2f;
float b = 0.3f;
map[a] = "sum";
std::cout << "Value for b: " << map[b] << std::endl; // Might not find the key
}
Here, a and b may not match due to the peculiarities of floating-point number representation.