c++ - 自定义类的自定义比较器,就像 STL

标签 c++ stl comparator

我有一个自定义类二叉搜索树。我想将比较器类作为参数传递(默认为 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 <对于将要使用它的类。我正在为那些类的源代码不可用的情况做准备

最佳答案

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

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

如果你想使用一个自定义的比较类作为一个相等的替代品,你必须在那个类中也有这样一个函数。

然后,您可以将其用作:

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

关于c++ - 自定义类的自定义比较器,就像 STL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24709075/

相关文章:

c++ - 如何从 lambda 表达式中获取函数指针?

c++ - 生成具有自定义分布的序列

c++ - std::array<T, 0> 的目的是什么?

java - 在 Java 中放置比较器类的最佳位置是哪里

java - 给定的测试数据比较器失败 - 为什么?

c++ - 帮助,澄清我对不合格名称查找 :ISO n3290 Draft 的疑问

c++ - tbb::concurrent_unordered_multimap 中的错误?即使是单线程,条目也会丢失

c++ - 初始化指针常量 vector

c++ - 有移动范围的算法吗?

c++ - 用排序仿函数实现多态性