2013-04-24 1 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(); 
    } 
} 

이 메인입니다 :

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*)' 

내가 '나오지 않았어 :이 긴 오류를 얻고있다

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

샘플을 수정하고 구조체로 유지하면 문제가 해결되지만 실제로 변환하지 않기 때문에 솔루션을 찾을 수 없습니다. nto 클래스.

+0

구조체 *는 * 클래스입니다. 즉, 객체가 필요할 때 포인터 (그리고 멤버 함수 포인터)를 사용하려고합니다. 예제에서와 같이 클래스/구조체 유형의 객체를 대신 사용하십시오. –

답변

4

세 번째 인수는 펑터라고하며 호출 할 수있는 것입니다. 함수 포인터, C++ 11 람다 또는 개체 멤버 함수 인 (포인터가 아님)입니다. CardComparer()를 사용하여, 위의 std::sort 통화에서

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

: 귀하의 경우

는 동적으로 힙에 펑터 오브젝트를 할당하지 않습니다, 그것은 std::sort 호출에서 임시 객체로 선언하는 충분 스택에 개체를 만듭니다.이 개체는 임시이며 std::sort이 실행되는 동안에 만 유효합니다. std::sort 함수는 이 개체를 호출합니다.이 개체는 개체에 operator() 함수를 호출하는 것과 같습니다. 이 비교 펑은 매우 간단하기 때문에

, 그것은 모든 데이터를 저장하는 데 필요하지 않습니다

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

그래서 멤버 데이터 필드에 대한 필요가 없습니다.

+0

고마워,하지만 방금 C++로 프로그래밍을 시작했고 클래스에 익숙하지 않았다. 따라서이 오류를 해결할 수있는 것은 무엇입니까? –

+0

고마워요! –

+0

실제로 그 연산자를 호출하지 않는다는 것을 깨달았습니다. 나는 의도적으로 cout << "test"; 연산자에서, 아무것도 인쇄되지 않습니다. –