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

hak*_*ami 2 c++ sorting templates stl

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

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;}
Run Code Online (Sandbox Code Playgroud)

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

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

当我使用sort函数时,我遇到了运行时错误.

我做错什么了吗?请帮我.

jua*_*nza 5

可能是这样的:

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

std::sort要求比较函数(在这种情况下,您的小于运算符)定义严格的弱排序.您的实现没有,因为它可能同时存在A < B并且B < A是真实的.