2011-03-17 48 views
1

今天,我寫了一篇關於使用std ::排序()來操作它含有類對象「向量」型的一些代碼,但我發現很多問題在編碼,請幫我找到解決辦法:如何對包含類對象的「vector」進行排序?爲什麼我錯了?

#include <vector> 
#include <algorithm> 

class Obj{ 
private: 
    int m_; 
public: 
    Obj():m_(0) {} 
    int act() { return m_; } 
    bool operator<(Obj obj) { 
     return this->act() < obj.act(); 
    } 
}; 
bool cmp(Obj a, Obj b) 
{ 
    return a.act() < b.act(); 
} 
bool cmpA(const Obj& a, const Obj& b) 
{ 
    return a.act() < b.act(); // @1 but wrong! 
} 
int foo() 
{ 
    std::vector<Obj> vobj; 
    // ... 
    std::sort(vobj.begin(),vobj.end(),cmp); // @2 well, it's ok. 
    std::sort(vobj.begin(),vobj.end());  // @3 but wrong! 
    return 0; 
} 

@ 1:爲什麼param的類型必須是'Obj'而不是'const Obj &'?但是當'Obj'是一個結構類型時,它不會出現錯誤,爲什麼?

@ 3:我有過載運算符'<',但這裏不能通過而compling。我錯過了什麼? 請幫助我,謝謝!

回答

3

使用std::sort時,您可以像選擇一樣通過比較器。如果沒有,std::sort將使用std::less作爲比較器,std::less默認使用operator<

您可以使用cmpA函子,但你只能訪問常量傳遞對象的成員函數 - 你有cmpA const引用他們。

class Obj{ 
private: 
    int m_; 
public: 
    Obj():m_(0) {} 
    int act() const { return m_; } // const member function, can be called on const objects or references 
}; 

bool operator<(Obj const & L, Obj const & R) { // The operator takes const references - it can compare const objects 
    return L.act() < R.act(); 
} 

使用這個類和運算符,可以調用std :: sort而不通過比較器。

+0

謝謝!我想我應該更仔細地檢查編譯器的消息! – 2011-03-17 17:20:45

2
int act() { return m_; } 

應該

int act() const { return m_; } 

bool operator<(Obj obj) { 
    return this->act() < obj.act(); 
} 

應該

bool operator<(const Obj& obj) const { 
    return this->act() < obj.act(); 
} 
相關問題