c++ - 如何在 double 组上定义比较运算符(小于)?

标签 c++ dictionary comparison-operators

我正在实现缓存以保存函数调用。

假设我有 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/

相关文章:

C++ "Floating Point Enum"

asp-classic - VBScript 函数可以返回字典吗?

javascript - 处理 Meteor 和 mongodb 中的嵌套字典

使用 Get-ChildItem 存储到数组时,Powershell Item-Property 未展开

for循环中的比较运算符(C语言)

c++ - 实现 clrscr() 函数以了解其工作原理

c++ - 为什么模板别名特化取决于引用它的上下文?

python - Python 中的内存问题。词典与数据库(或者你能把两者结合起来吗?)

javascript - 如何检查数组元素是否大于特定值

C++ 通过 Const 引用传递并通过 Const 引用返回