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

我与影子孤独终老i 提交于 2020-01-15 05:21:34

问题


I have a self-define class using template, like this:

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;}

Now, I new some foos and give them value, then I want to sort this array:

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

When I use sort function, I got a run-time error.

Did I do something wrong? Please help me.


回答1:


Probably like this:

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

std::sort requires that the comparison function (your less-than operator in this case) defines a strict weak ordering. Your implementation does not, because it is possible for both A < B and B < A to be true.




回答2:


If T is castable to bool,

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

will return true always except a == f.a. Maybe you need something like:

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

Obviously, runtime error occurs because your less operator is incorrect for sort function.



来源:https://stackoverflow.com/questions/12555891/how-to-overload-less-operator-in-a-template-class-for-sort-algorithm-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!