Vastor
Vastor

Reputation: 77

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

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?

Upvotes: 2

Views: 1032

Answers (2)

Paul Varghese
Paul Varghese

Reputation: 1655

use list member function sort

students.sort(compare);

Upvotes: 3

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

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

Upvotes: 11

Related Questions