Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't std::sort doesn't work on std::list?

Tags:

c++

Due to std::sort on a std::list, I receive the following errors:

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

What causes these errors? How can I sort this list?

like image 483
Vastor Avatar asked Jun 30 '26 03:06

Vastor


2 Answers

Your error means that the sort function was trying to use subtraction on the iterators. Only random access iterators support this operation. std::list has Bi-Directional iterators. std::sort only works with random access iterators. Luckily, std::list has it's own sort function.

students.sort(compare);
like image 81
Benjamin Lindley Avatar answered Jul 01 '26 18:07

Benjamin Lindley


use list member function sort

students.sort(compare);
like image 24
Paul Varghese Avatar answered Jul 01 '26 19:07

Paul Varghese