如何解决此C ++ Vector Sorting错误?

时间:2012-01-19 05:23:20

标签: c++ sorting vector

这是我尝试编译的问题代码:

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)]

它为剩下的四种排序重复此错误。我不明白,我基本上是从这里复制/粘贴此解决方案:http://www.cplusplus.com/reference/algorithm/sort/

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:8)

您需要将simpleComparator声明为static方法,否则它将不符合std::sort所期望的类型。

为完全正确,您还应将其作为TeamMatcher::simpleComparator传递,有关详细信息,请参阅here

答案 1 :(得分: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
}

这可能会让人感到困惑,因为你不会明白如何比较两个学生(GPA,出勤率,可用时间,身高,智商,等等......)

相关问题