2013-04-24 44 views
0

從這裏舉個例子: http://www.cplusplus.com/reference/algorithm/sort/使用類:排序()

可見

struct myclass { 
    bool operator() (int i,int j) { return (i<j);} 
} myobject; 

int main() { 
    int myints[] = {32,71,12,45,26,80,53,33}; 
    std::vector<int> myvector (myints, myints+8);    // 32 71 12 45 26 80 53 33 

    // using object as comp 
    std::sort (myvector.begin(), myvector.end(), myobject);  //(12 26 32 33 45 53 71 80) 
} 

這工作得很好,但是我想使用的,而不是結構類。那麼,我做的是:

CardComparer類:

bool CardComparer::operator() (Card* firstCard, Card* secondCard) { 
    this->firstCard = firstCard; 
    this->secondCard = secondCard; 
    if (firstCard->GetRank() == secondCard->GetRank()) { 
     return firstCard->GetSuit() > secondCard->GetSuit(); 
    } 
    else { 
     return firstCard->GetRank() > secondCard->GetRank(); 
    } 
} 

,這是主要的:

CardComparer* compare; 
compare = new CardComparer(); 
sort(cards.begin(), cards.end(), compare->operator()); 

我得到這個長的錯誤:

hand.cpp: In member function 'void Hand::AddCard(Card*)': 
hand.cpp:60:54: error: no matching function for call to 'sort(std::vector<Card*>::iterator, std::vector<Card*>::iterator, <unresolved overloaded function type>)' 
hand.cpp:60:54: note: candidates are: 
In file included from /usr/include/c++/4.7/algorithm:63:0, 
       from hand.cpp:4: 
/usr/include/c++/4.7/bits/stl_algo.h:5463:5: note: template<class _RAIter> void std::sort(_RAIter, _RAIter) 
/usr/include/c++/4.7/bits/stl_algo.h:5463:5: note: template argument deduction/substitution failed: 
hand.cpp:60:54: note: candidate expects 2 arguments, 3 provided 
In file included from /usr/include/c++/4.7/algorithm:63:0, 
       from hand.cpp:4: 
/usr/include/c++/4.7/bits/stl_algo.h:5499:5: note: void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = __gnu_cxx::__normal_iterator<Card**, std::vector<Card*> >; _Compare = bool (CardComparer::*)(Card*, Card*)] 
/usr/include/c++/4.7/bits/stl_algo.h:5499:5: note: no known conversion for argument 3 from '<unresolved overloaded function type>' to 'bool (CardComparer::*)(Card*, Card*)' 

我不能」噸真的找到一個解決方案,因爲如果我修改該示例,並保持它作爲一個結構它工作正常,但不工作時,我轉換它我nto類。

+0

結構*是*一類。你的意思是當你需要一個對象時你試圖使用一個指針(然後是一個成員函數指針)。如示例所示,使用類/結構類型的對象。 – 2013-04-24 02:14:38

回答

4

第三個參數被稱爲仿函數,它可以被調用。一個指向函數的指針,一個C++ 11 lambda或一個對象實例(非指針)與一個operator()成員函數。

在你的情況下,不要動態分配堆上的仿函數對象,它足以聲明它作爲std::sort調用一個臨時對象:

std::sort(cards.begin(), cards.end(), CardComparer()); 

在上面std::sort通話,使用CardComparer()在堆棧上創建一個對象,該對象是臨時的,僅在std::sort正在運行時有效。 std::sort函數將調用這個對象,這與調用對象的operator()函數相同。

由於這種比較仿函數是非常簡單的,它並不需要存儲任何數據:

struct CardComparer 
{ 
    bool operator() (const Card* firstCard, const Card* secondCard) const { ... } 
}; 

所以沒必要爲會員數據字段。

+0

謝謝,但我剛剛開始使用C++編程,並且剛入門。那麼,有什麼可以解決這個錯誤? – 2013-04-24 01:30:52

+0

感謝它的工作! – 2013-04-24 01:36:12

+0

我意識到它實際上並沒有調用該操作符。我故意把cout <<「測試」;在運營商,並沒有打印出來。 – 2013-04-24 01:50:24