Floating point keys in std:map(std:map 中的浮点键)
问题描述
下面的代码应该在存在的 std::map
中找到键 3.0
.但由于浮点精度,它不会被找到.
The following code is supposed to find the key 3.0
in a std::map
which exists. But due to floating point precision it won't be found.
map<double, double> mymap;
mymap[3.0] = 1.0;
double t = 0.0;
for(int i = 0; i < 31; i++)
{
t += 0.1;
bool contains = (mymap.count(t) > 0);
}
在上面的例子中,contains
总是false
.我目前的解决方法是将 t
乘以 0.1 而不是添加 0.1,如下所示:
In the above example, contains
will always be false
.
My current workaround is just multiply t
by 0.1 instead of adding 0.1, like this:
for(int i = 0; i < 31; i++)
{
t = 0.1 * i;
bool contains = (mymap.count(t) > 0);
}
现在的问题:
如果我使用 double
键,有没有办法向 std::map
引入模糊比较?浮点数比较的常见解决方案通常类似于 a-b <;epsilon
.但是我没有看到使用 std::map
来做到这一点的直接方法.我真的必须将 double
类型封装在一个类中并覆盖 operator<(...)
来实现这个功能吗?
Is there a way to introduce a fuzzyCompare to the std::map
if I use double
keys?
The common solution for floating point number comparison is usually something like a-b < epsilon
. But I don't see a straightforward way to do this with std::map
.
Do I really have to encapsulate the double
type in a class and overwrite operator<(...)
to implement this functionality?
推荐答案
您可以实现自己的比较功能.
You could implement own compare function.
#include <functional>
class own_double_less : public std::binary_function<double,double,bool>
{
public:
own_double_less( double arg_ = 1e-7 ) : epsilon(arg_) {}
bool operator()( const double &left, const double &right ) const
{
// you can choose other way to make decision
// (The original version is: return left < right;)
return (abs(left - right) > epsilon) && (left < right);
}
double epsilon;
};
// your map:
map<double,double,own_double_less> mymap;
更新:参见有效 STL 中的第 40 项!根据建议更新.
Updated: see Item 40 in Effective STL! Updated based on suggestions.
这篇关于std:map 中的浮点键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std:map 中的浮点键


基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01