pokey909 - 14 days ago 7

C++ Question

The following code is supposed to find the key

`3.0`

`std::map`

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

}

In the above example,

`contains`

`false`

My current workaround is just multiply

`t`

`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`

`double`

The common solution for floating point number comparison is usually something like

`a-b < epsilon`

`std::map`

Do I really have to encapsulate the

`double`

`operator<(...)`

Answer

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

Updated: see Item 40 in Effective STL! Updated based on suggestions.

Source (Stackoverflow)

Comments