【问题标题】:Custom comparator for custom class, just like STL自定义类的自定义比较器,就像 STL
【发布时间】:2014-07-12 02:32:51
【问题描述】:

我有一个自定义类二进制搜索树。我想将比较器类作为参数传递(默认为 std::less)。我搜索的大多数答案都使用 STL 对象,然后传递它们的自定义比较器。我想要一些不同的东西。

// 树类

template <class T,class Compare = less<T>>
class Tree
{
    struct TreeNode
    {
        T data;
        struct TreeNode *  left;
        struct TreeNode *  right;
    };
public:
    void insert(T);
};

// 自定义比较器类

template <class T>
class CustomCompare
{
public:
    bool compare(const T&, const T &);
};


template<class T>
bool CustomCompare<T>::compare(const T & a, const T &b)
{
    cout << "calling custom comparator";
    return a<b;
}

// 插入树中

template<class T,class Compare>
void Tree<T,Compare>::insert(T val)
{
      // HOW DO I CALL COMPARE HERE? I tried this
      if (compare(val->data , treeNode->data))  /// does not work.
       // I get error - use of undeclared identifier compare.


      //IF I DO THIS, I get error - expected unqualified id
       Compare<T> x; // cannot create instance of Compare

      // IF I DO THIS< I can create instance of Compare but cannot call function compare.
       Compare x;

       x.compare(....) -- Error no member named compare in std::less


}

我无法将 CustomCompare::compare 设为静态,因为我希望代码也适用于 std::less。

我希望问题很清楚。

注意:我知道我可以为将要使用它的类重载operator &lt;。我正在为这些类的源代码不可用的情况做准备

【问题讨论】:

  • 你必须创建一个Compare的实例。
  • 如果我这样做,我会收到错误:在 std::less 中没有名为 compare 的成员

标签: c++ stl comparator


【解决方案1】:

std::less 具有以下功能来比较对象。

bool operator()( const T& lhs, const T& rhs ) const;

如果您想使用自定义比较类作为同等替代品,则该类中也必须有这样的功能。

然后,您可以将其用作:

  if (compare()(val->data , treeNode->data))

【讨论】:

  • 工作就像一个魅力。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-07
  • 2021-03-17
  • 2017-11-02
  • 2023-03-31
  • 2015-06-21
相关资源
最近更新 更多