map std 浮点数索引_std:map中的浮点键

The following code is supposed to find the key 3.0in a std::map which exists. But due to floating point precision it won't be found.

map 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);

}

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

}

Now the question:

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

解决方案

You could implement own compare function.

#include

class own_double_less : public std::binary_function

{

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 mymap;

Updated: see Item 40 in Effective STL!

Updated based on suggestions.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值