2

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

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

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

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

当我使用排序功能时,出现运行时错误。

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

4

2 回答 2

5

大概是这样的:

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

std::sort要求比较函数(在这种情况下是小于运算符)定义严格的弱排序。您的实现没有,因为两者都可能A < BB < A真的。

于 2012-09-23T20:20:21.443 回答
4

如果 T 可转换为 bool,

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

将始终返回 true 除了 a == fa 也许你需要类似的东西:

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

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

于 2012-09-23T20:20:56.303 回答