2009-07-09 5 views
1

std :: sort 알고리즘을 사용하는 데 문제가 있습니다. 클래스를 정렬하기 위해보다 적은 연산자를 오버로드 할 수 있다고 읽었지만 모든 종류의 오류가 발생했습니다. 아래 예제에서 볼 수있는 것처럼 functor를 사용하여 시도해 보았습니다.STL 정렬 알고리즘에 대한 도움이 필요하십니까

나는 누군가가 내가 여기서 잘못하고있는 것을 볼 수 있기를 바랬다.

#include <iostream> 
#include <vector> 
#include <algorithm> 

#include <stdlib.h> 
#include <time.h> 

class Thing { 
public: 
    Thing(int val) { 
     this->_val = val; 
    } 

    bool operator<(Thing& rhs) { 
     std::cout << "this works!"; 
     return this->val() < rhs.val(); 
    } 

    int val() { 
     return this->_val; 
    } 
protected: 
    int _val; 
}; 

struct Sort { 
    bool operator()(Thing& start, Thing& end) { 
     return start.val() < end.val(); 
    } 
}; 

int main (int argc, char * const argv[]) { 
    std::srand(std::time(NULL)); 

    std::vector<Thing> things; 
    for(int i = 0; i < 100; i++) { 
     Thing myThing(std::rand()); 
     things.push_back(myThing); 
    } 

    if(things[1] < things[2]) { 
     //This works 
    } 

    //std::sort(things.begin(), things.end()); //This doesn't 

    //std::sort(things.begin(), things.end(), Sort()); //Neither does this 

    for(int i = 0; i < 100; i++) { 
     std::cout << things.at(i).val() << std::endl; 
    } 

    return 0; 
} 

답변

3

난 당신이

int val() const { 

bool operator()(const Thing& start, const Thing& end) { 

int val() { 

bool operator()(Thing& start, Thing& end) { 

을 변경해야합니다 생각 0

IOW, 코드가 const-correct 일 필요가 있고 사실상 수정할 필요가 없다고 주장하지 않아야합니다.

4

val()operator<()const 기능을합니다.

Sort::operator()과 동일 - Thing& 대신 const Thing&을 사용하십시오.

+0

'opeartor <()'대신에'연산자 <()'입니다. 픽스가 너무 작기 때문에 편집 할 수 없습니다. – lucas92

+0

고침. 고마워. – Paul

0

< 연산자를 const 참조로 사용하도록하십시오. const 멤버 함수가 non-const 함수를 호출 할 수 없기 때문에 _val에 직접 액세스하거나 (바람직하게) val() const를 직접 구현하도록 구현을 변경해야합니다.

관련 문제