2011-12-06 45 views
2

由于std::sortstd::list,我收到以下错误:为什么不std :: sort在std :: list上不起作用?

 
line 44   : instantiated from here 
line 5258 : error: no match for 'operator-' in '_last -__first' 
line 179 : note: candidates are: ptrdiff_t std::operator-(const std::_Bit_iterator_base&, const std::_Bit_iterator_base&) 

从下面的代码:

int main() 
{ 
    std::list<Student_info> students; 
    Student_info record; 
    string::size_type maxlen = 0; // the length of the longest name 

    // read and store all the students data. 
    while (read(cin, record)) 
    { 
     // find length of longest name 
     maxlen = max(maxlen, record.name.size()); 
     students.push_back(record); 
    } 

    // alphabetize the student records 
    std::sort(students.begin(), students.end(), compare); 

    return 0; 
} 

是什么原因导致这些错误?我怎样才能整理这个列表?

回答

10

你的错误意味着排序函数试图对迭代器使用减法。只有随机访问迭代器支持此操作。 std::list有双向迭代器。 std::sort只适用于随机访问迭代器。幸运的是,std::listhas it's own sort function

students.sort(compare); 
+0

理解的答案,是这么认为的,还有一些我不明白(个人知识基地),以后我可以从书中学习的思想更长时间后弄清楚,所以没问题,无论如何,tq的答案... – Vastor

3

使用列表的成员函数排序

students.sort(compare); 
相关问题