本文介绍了如何重载更少的操作符在模板类中的排序算法使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个使用模板的自定义类,例如: template< class T& class foo { public: T a; bool operator<(const foo< T>& f); //其他函数... } 模板< class T> bool foo< T> :: operator<(const foo< T>& f) {return a - fa;} 现在,我新建一些foos并赋予它们值,然后我想对这个数组进行排序: foo< int> * fp = new foo< int> [3]; //给每个元素值 sort(fp,fp + 3); //运行时错误 当我使用排序函数时,我得到一个运行时错误。 / p> 我做错了吗?请帮助我。解决方案可能如下: template< class T> bool foo< T> :: operator<(const foo< T>& f) {return a< fa;} std :: sort 比较函数(在此情况下,小于运算符)定义了严格弱排序。您的实现不会,因为它可能 A< B 和 B 为真。 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 valuesort(fp, fp+3); //run-time errorWhen I use sort function, I got a run-time error.Did I do something wrong? Please help me. 解决方案 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. 这篇关于如何重载更少的操作符在模板类中的排序算法使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 14:59