如何在模板类中重载较少运算符以供排序算法使用

How to overload less operator in a template class for sort algorithm use?

本文关键字:运算符 排序 算法 重载      更新时间:2023-10-16

我有一个使用模板的自定义类,如下所示:

template<class T>
class foo 
{
    public:
    T a;
    bool operator<(const foo<T> &f);
    //other functions...
}
template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a - f.a;}

现在,我新建了一些 foos 并赋予它们值,然后我想对这个数组进行排序:

foo<int>* fp = new foo<int>[3];
//give each element value
sort(fp, fp+3); //run-time error

当我使用排序函数时,我遇到了运行时错误。

我做错了什么吗?请帮助我。

大概是这样的:

template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a < f.a;}

std::sort要求比较函数(在本例中为小于运算符)定义严格的弱排序。您的实现不会,因为A < BB < A都可能为真。

如果 T 可投射到布尔值,

template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a - f.a;}

将始终返回 true,除了 == f.a。也许你需要这样的东西:

template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a < f.a;}

显然,发生运行时错误是因为您的 less 运算符对排序函数不正确。