2012-01-19 10 views
5

は、私がコンパイルしようとしてる問題のコードです:このC++ Vector Sortingエラーをどのように克服できますか?ここ

bool TeamMatcher::simpleComparator(Student first, Student second){ 
    return (first.numberOfHrsAvailable < second.numberOfHrsAvailable); 
} 

void TeamMatcher::sortRosters(){ 
    sort(rosterExcellent.begin(), rosterExcellent.end(), simpleComparator); 
    sort(rosterGood.begin(), rosterGood.end(), simpleComparator); 
    sort(rosterOK.begin(), rosterOK.end(), simpleComparator); 
    sort(rosterPoor.begin(), rosterPoor.end(), simpleComparator); 
    sort(rosterNoSay.begin(), rosterNoSay.end(), simpleComparator); 
} 

次に、ここで私は取得していますエラー:

TeamMatcher.C: In member function ‘void TeamMatcher::sortRosters()’: 
TeamMatcher.C:51: error: no matching function for call to ‘sort(__gnu_cxx::__normal_iterator<Student*, std::vector<Student, std::allocator<Student> > >, __gnu_cxx::__normal_iterator<Student*, std::vector<Student, std::allocator<Student> > >, <unresolved overloaded function type>)’ 
/usr/include/c++/4.2.1/bits/stl_algo.h:2852: note: candidates are: void std::sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Student*, std::vector<Student, std::allocator<Student> > >, _Compare = bool (TeamMatcher::*)(Student, Student)] 

それは、残りの4つの種類のために、このエラーが繰り返されます。私は理解していません。基本的には、ここからこのソリューションをコピーして貼り付けています:http://www.cplusplus.com/reference/algorithm/sort/

ご協力いただけると助かります。

+3

'namespace std;'を使用して名前空間の指示文をファイルに追加しましたか? 'std'名前空間を' std :: sort'としてアルゴリズムの名前を品質化する必要がない場合は、ファイルに追加しましたか? –

+0

少なくとも私の.hファイルで、この.Cファイルにインポートしました。それでもいいよね? –

+2

@Als - コンパイラの出力から、すでに 'std :: sort'が候補になっていることがわかります。これは問題ではないことを意味しています。 – tzaman

答えて

8

simpleComparatorstaticメソッドとして宣言する必要があります。それ以外の場合は、std::sortで期待されるタイプに適合しません。

完全に正確であるためには、TeamMatcher::simpleComparatorとして渡す必要があります(詳細はhereを参照)。

+0

Aha!どうもありがとうございました!これはそれを修正しました!人生で勝つ道 –

+0

あなたは大歓迎です! :) – tzaman

1

代わりに比較関数のためにこれを試してみてください:

bool simpleComparator(const Student& first, const Student& second){ 
    return (first.numberOfHrsAvailable < second.numberOfHrsAvailable); 
} 

比較関数は、あなたのTeamMemberクラスのメンバーではないことに注意してください、そして防止でのconst参照不要なコピーを渡します。

あなたはさらに一歩を取ると、学生

bool Student::operator<(const Student& first, const Student& second) 
{ 
    return (first.numberOfHrsAvailable < second.numberOfHrsAvailable); 
} 

ための比較方法を定義することができます今、あなたは自分の生徒にソート呼び出すことができますし、それが使用する比較方法があるでしょう:

std::sort(studentIter.begin(), studentIter.end()); 

しかし、このケースでは、常に学生を利用可能な時間数と比較しない限り、最初の方法をお勧めします。例えば、これは他のプログラマに混乱することがあります。

if (studentA < studentB) 
{ 
    // Do stuff 
} 

それはあなたが2人の学生(GPA、出席、時間が利用可能、高さ、IQ、何を...)を比較する方法を容易に明らかではないので、それが混乱を招くことがあり

関連する問題