std::map Floating-Point Key Comparison
Using floating-point values as keys in std::maps can pose challenges due to the inherent imprecision of floating-point arithmetic. One common issue is that comparing floating-point keys using strict equality (==) may not always work as expected, as even seemingly exact values may not match due to precision error.
In the given code example, the loop attempts to find the key 3.0 in a std::map, but fails because the loop increments the search key using += 0.1, which may not precisely match the expected key value due to floating-point precision inaccuracies.
To address this issue, you could use the std::setprecision function in your program to specify the number of decimal places to consider when comparing keys. However, this approach can still be unreliable because it doesn't guarantee that the keys will compare exactly.
A better solution is to use an approximate comparison function in your std::map. You can define a custom comparator that uses an epsilon threshold to determine key equality. This allows you to compare keys within a certain tolerance, effectively ignoring minor precision differences:
struct fuzzy_double_comparator { bool operator() (const double a, const double b) const { return std::fabs(a - b) < epsilon; } };
This comparator function can then be passed to the std::map constructor to use the approximate comparison:
std::map<double, double, fuzzy_double_comparator> mymap;
With this approach, you can find the key 3.0 in the std::map even if its actual value is slightly different due to floating-point precision limitations.
以上是如何將'std::map”與浮點鍵一起使用:比較不準確的解決方案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!