c++ - 为什么 std::sort 对 std::list 不起作用?

标签 c++

由于 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&)

From the following code:

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;
}

是什么导致了这些错误?我该如何排序这个列表?

最佳答案

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

students.sort(compare);

关于c++ - 为什么 std::sort 对 std::list 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8400735/

相关文章:

c++ - 有什么方法可以使用 GCC 的 __thread 完全模拟 thread_local 吗?

c++ - 为什么我可以在私有(private)类型上使用 auto ?

c++ - 为什么不能用 typedef 类型定义 Qt 信号的参数?

c++ - 帮助改进这个INI解析代码

c++ - glutBitmapString/glutStrokeString 似乎需要 const unsigned char* - 字符串不起作用

C++ std::string::find 总是返回 npos?

c++ - 在类构造函数中初始化 protected 常量

c++ - Boost:使用运算符[]访问bimap

c++ - gluPickMatrix - 出了点问题,一个对象总是在现场

c++ - 阅读通过 PuTTY 传递的低级鼠标点击 Unix