2011-02-24 39 views
11
class MyClass { 
    public: 
    int a; 
    bool operator<(const MyClass other) const { 
     return a<other.a; 
    } 
    .... 
}; 
.... 
QList<MyClass*> list; 

回答

12

到问题的一般解决办法是让通用低于函数对象,简单地转发到指向的类型的小于操作符。喜欢的东西:

template <typename T> 
struct PtrLess // public std::binary_function<bool, const T*, const T*> 
{  
    bool operator()(const T* a, const T* b) const  
    { 
    // may want to check that the pointers aren't zero... 
    return *a < *b; 
    } 
}; 

你可以再做:

qSort(list.begin(), list.end(), PtrLess<MyClass>()); 
6

在C++ 11你也可以使用这样的拉姆达:

QList<const Item*> l; 
qSort(l.begin(), l.end(), 
     [](const Item* a, const Item* b) -> bool { return a->Name() < b->Name(); }); 
相关问题