2011-02-24 133 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(); }); 
相關問題