问题
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