我正在实现缓存以保存函数调用。
假设我有 2 double
我的函数调用的参数。
那些必须是某些 LRU 缓存的键,或者 - 使其更简单 - C++ std::map
.
所以我创建了一个模板类,里面有数组(值的数量可变)
template <int n>
class DoubleArray
{
public:
double array[n];
};
当尝试将其用作我的 std::map
的 key 时, 编译器提示因为它需要 operator<
对于那些。
.....\include\c++\7.3.1\bits\stl_function.h:386:20: note:
'const DoubleArray<2>' is not derived from 'const std::map<_Key, _Tp, _Compare,
_Alloc>'
{ return __x < __y; }
~~~~^~~~~
所以我实现了一个比较运算符(好吧,我认为散列可以解决问题,但它似乎并非如此......)并编译:
#include <map>
template <int n>
class DoubleArray
{
public:
double array[n];
bool operator<(const DoubleArray &other) const
{
return (array[0] < other.array[0]) || (array[0] == other.array[0] && array[1] < other.array[1]);
}
};
int main()
{
std::map<DoubleArray<2>,double> my_cache;
DoubleArray<2> params;
// clumsy way to initialize the array...
params.array[0] = 12;
params.array[1] = 2;
// put a value in cache
my_cache[params] = 23;
}
请注意,比较运算符非常笨拙。如果我有 6 个参数怎么办(这是我的真实情况)。
如何创建通用比较运算符(可能使用模板递归)?
如果这是一个 XY 问题,是否有更简单的方法来使用 double
创建 n 值键映射?类型?
(请注意,我完全知道使用 double
值作为键看起来很糟糕,但我的目标是在参数完全相同的函数调用上缓存值,这些值不打算存储等)
最佳答案
您正在寻找std::lexicographical_compare
bool operator<(const DoubleArray &other) const
{
return std::lexicographical_compare(array, array + n, other.array, other.array + n);
}
或者,您可以只为 std::array
定义一个别名,它已经定义了所有比较运算符
template<int n>
using DoubleArray = std::array<double, n>;
关于c++ - 如何在 double 组上定义比较运算符(小于)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53637613/