list 比较函数的重载
程序代码:
#include <iostream> #include <list> using namespace std; class Test { public: Test(int a=0) { this->data_ = a; } ~Test() {} int data() {return this->data_;} void data(int a) { this->data_ = a; } bool operator < (Test* right) const { return this->data_ <= right->data(); } private: int data_; }; typedef std::list<Test*> TestList; template<> struct std::greater<Test*> { bool operator()( Test*_X, Test* _Y) const { return (_X->data() > _Y->data()); } }; int main() { TestList a; int i = 0; Test *p[5]; p[0] = new Test(65); p[1] = new Test(34); p[2] = new Test(45); p[3] = new Test(23); p[4] = new Test(28); a.push_back(p[0]); a.push_back(p[1]); a.push_back(p[2]); a.push_back(p[3]); a.push_back(p[4]); a.sort(greater<Test*>()); TestList::iterator iter = a.begin(); for(; iter != a.end(); ++iter) cout<<(*iter)->data() << " "; cout <<endl; return 0; }为什么上述的STL定义体中的template<>没有参数呢 ?
template<>
struct std::greater<Test*>
{
bool operator()( Test*_X, Test* _Y) const
{
return (_X->data() > _Y->data());
}
};