在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有一些奇怪的事情,但范围检查不包括这些)。
显然,如果您使用==来搜索一个不等于多映射中的任何值的值,它将找不到。如果你把两个尽可能接近的值相加,它们都会相加。
相关文章:
- 使用std::multimap迭代器创建std::list
- std::multimap<std::chrono::milliseconds, T>::rbegin 在 MSVS-13 中指向 end()?
- C++在使用std::multimap时出现运行时错误的几率很小
- 用 C++20 的给定键读取/写入 std::multimap 的所有值?
- std::multimap::erase() 在迭代时
- 访问 std::multimap 值的最佳方式?
- MAP和Multimap之间的C 模板专业化
- 如何使用 std::multimap 将整数键映射到两个用作多维数组坐标的整数值(对于井字)?
- "std::multimap"是否保证每个键的实际值在相等范围内?
- 无法插入qcustomplot :: qcpgraph中的Multimap C
- 特定键在 std::multimap 中出现的次数
- swig:std/multimap.i似乎打破了TCL包装
- 如何使用"std::multimap"或任何其他容器对多个值进行排序?
- c++ 为什么 std::multimap 比 std::p riority_queue 慢
- 检查multimap c++中是否已经存在值
- std :: multimap :: emplace覆盖旧键
- 初始化静态std :: multimap在其中声明的方法
- ISO C 禁止没有类型的“ Multimap”声明
- 我从std :: multimap.lower_bound获得了无效的指针
- 哪个元素将从 std::multimap::find 返回,同样,std::multiset::find