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

时间:2012-09-23 20:15:33

标签: c++ templates sorting 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;}

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

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

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

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

2 个答案:

答案 0 :(得分:5)

可能是这样的:

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

std::sort要求比较函数(在本例中为less-than运算符)定义strict weak ordering。您的实施没有,因为A < BB < A都可以为真。

答案 1 :(得分:4)

如果T可以施放到布尔,

template<class T>
bool foo<T>::operator<(const foo<T> &f)
{return a - f.a;}
除了a == f.a之外,

将始终返回true。也许你需要这样的东西:

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

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