gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:07 33 4
gpt4 key购买 nike

我有一个自定义类二叉搜索树。我想将比较器类作为参数传递(默认为 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com