[英]Why doesn't std::sort doesn't work on std::list?
由于std::list
上的std::sort
,我收到以下错误:
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;
}
是什么导致这些错误? 我该如何排序这个清单?
您的错误意味着sort函数试图在迭代器上使用减法。 只有随机访问迭代器才支持此操作。 std::list
具有双向迭代器。 std::sort
仅适用于随机访问迭代器。 幸运的是, std::list
拥有自己的排序功能 。
students.sort(compare);
使用列表成员函数排序
students.sort(compare);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.