Jea*_*bre 3 c++ dictionary comparison-operators
我正在实现一个缓存来保存函数调用.
假设double我的函数调用有2个参数.
这些必须是某些LRU缓存的关键,或者 - 更简单 - 一个C++ std::map.
所以我创建了一个内部数组的模板类(可变数量的值)
template <int n>
class DoubleArray
{
public:
double array[n];
};
Run Code Online (Sandbox Code Playgroud)
当尝试将其用作我的关键时std::map,编译器抱怨,因为它需要一个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; }
~~~~^~~~~
Run Code Online (Sandbox Code Playgroud)
所以我实现了一个比较运算符(好吧,我虽然哈希可以做到这一点,但它似乎不是这样......)并且它编译:
#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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,比较运算符非常笨拙.如果我有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);
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以只定义一个别名std::array,该别名已经定义了所有比较运算符
template<int n>
using DoubleArray = std::array<double, n>;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
193 次 |
| 最近记录: |