我正在实现一个缓存来保存函数调用。

假设我的函数调用有 2 个 double 参数。

这些必须是某些 LRU 缓存的键,或者 - 使其更简单 - C++ std::map

所以我创建了一个模板类,里面有数组(可变数量的值)

template <int n>
  class DoubleArray
  {
    public:
    double array[n];
   };

当尝试使用它作为我的 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; }
                ~~~~^~~~~

所以我实现了一个比较运算符(好吧,我认为散列可以解决问题,但似乎并非如此......)并编译:
#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::array 来回避这个问题。使用 alias declaration 您的代码可以简化为

template <std::size_t N>
using DoubleArray = std::array<double, N>;

int main()
{
   std::map<DoubleArray<2>,double> my_cache;
   my_cache[{12, 2}] = 23;
}

关于c++ - 如何在 double 数组上定义比较运算符(小于)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53637613/

10-12 00:07
查看更多