在multimap中用作键的浮点值

float value used as a key in multimap

本文关键字:multimap      更新时间:2023-10-16

如果在float之间进行比较,我认为不能只是使用equal ==,需要检查是否abs(a-b) <ε。那么当float类型的value被用作键时,我们可以使用equal_range函数吗?>

:

std::multimap<float, string>  ds;
ds.insert(make_pair(2.0, string("a")));
ds.insert(make_pair(2.0, string("b")));
ds.insert(make_pair(3.0, string("d")));
ds.equal_range(2.0)

std::multimap::equal_range实际上根本不是使用operator==计算的。仅用<>计算。它实际上是两个迭代器,第一个是std::multimap::lower_bound(第一个元素不小于给定键),第二个是std::multimap::upper_bound(第一个元素大于给定键)。

所以与float double 一起使用是非常安全的。

测试一下,你会发现它显然是有效的。

#include    <map>
#include    <string>
#include    <iostream>
int main()
{
    std::multimap<float, std::string>  ds;
    ds.emplace(2.0f, std::string("a"));
    ds.emplace(2.0f, std::string("b"));
    ds.emplace(3.0f, std::string("d"));
    auto r = ds.equal_range(2.0f);
    for ( auto it = r.first; it != r.second; ++it )
        std::cout << it->second << std::endl;
}
输出:

a
b

您可以为float定义自己的less -操作符。请看下面的例子:

// http://www.cplusplus.com/reference/map/multimap/
#include <map>
#include <cassert>
#include <iostream>
#include <algorithm>
class CApproxFloatLess {
    double m_eps;
public:
    CApproxFloatLess(float eps) :
    m_eps(eps)
    {
        assert(eps >= 0);
    }
    bool operator () (float x, float y) const {
        return x + m_eps*(1+std::abs(x)) < y;
    }
};
template <class It>
void info(float x, It& it) {
    std::cout << "Found pair (" << it->first << ", " << it->second << ") for " << x << ".n";
}
int main() {
    typedef std::multimap<float,std::string,CApproxFloatLess> MyMap;
    MyMap ds(CApproxFloatLess(1e-3));
    ds.insert(make_pair(2.0, std::string("a")));
    ds.insert(make_pair(2.0, std::string("b")));
    ds.insert(make_pair(3.0, std::string("d")));

    float x=2.001;
    MyMap::iterator it=ds.find(x);
    if( it != ds.end() )
        info(x,it);
    x=1.999;
    it=ds.find(x);
    if( it != ds.end() )
        info(x,it);
    x=2.01;
    it=ds.find(x);
    if( it != ds.end() )
        info(x,it);
    x=3.001;
    it=ds.find(x);
    if( it != ds.end() )
        info(x,it);
    return 0;
}

程序的输出是:

Found pair (2, a) for 2.001.
Found pair (2, a) for 1.999.
Found pair (3, d) for 3.001.

谁说不能用==比较两个浮点数?==适用于浮点数;如果它们相等,则返回true,如果它们不同,则返回false。(NaN和负0有一些奇怪的事情,但范围检查不包括这些)。

显然,如果您使用==来搜索一个不等于多映射中的任何值的值,它将找不到。如果你把两个尽可能接近的值相加,它们都会相加。