2009-07-09 27 views
1

ここでstd :: sortアルゴリズムを使用する際にいくつか問題があります。私はあなたがクラスをソートするために演算子をあまりにもオーバーロードすることができますが、私はあらゆる種類のエラーを取得していることを読んでいた。また、私が下で作った例のように、ファンクタを使ってみました。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 <()'ではなく 'operator <()'です。修正が小さすぎるため編集できませんでした。 – lucas92

+0

修正しました、ありがとうございます。 – Paul

0

オペレータ<をconst参照で引数にしてみてください。 constメンバ関数がconst以外のものを呼び出せないため、これを行うときに、_valに直接アクセスするか、(好ましくは)val()constにアクセスするようにその実装を変更する必要があります。