注册 登录
编程论坛 C++教室

list 比较函数的重载

vfdff 发布于 2010-11-28 00:41, 1049 次点击
程序代码:
#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());
    }
};
3 回复
#2
玩出来的代码2010-11-28 14:40
本不需要参数,模板的特化。
#3
pangding2010-11-28 19:35
呵呵,不看这代码估计这語法我也想不起来了~~
#4
vfdff2010-12-08 00:47
a.push_back(NULL);有效
1