Home > Backend Development > C++ > Why Does `std::sort` Fail to Sort a `std::list` of Structures?

Why Does `std::sort` Fail to Sort a `std::list` of Structures?

Linda Hamilton
Release: 2024-11-10 22:00:03
Original
571 people have browsed it

Why Does `std::sort` Fail to Sort a `std::list` of Structures?

Sorting a List with STL Sort Function: An Implementation Issue

When attempting to sort a list of structures using the std::sort function, you may encounter a compilation error indicating a missing operator-. This error arises when the supplied comparator, SortDescending, operates on elements of a std::list, which supports bidirectional iterators rather than random access iterators needed by std::sort.

To resolve this issue, instead of using std::sort, employ the std::list<>::sort member function, which is designed to handle lists specifically. Here's the modified code using std::list<>::sort:

Result.poly.sort(SortDescending());
Copy after login

Note that the std::list<>::sort member function also requires a comparator function. The SortDescending comparator remains unchanged:

struct SortDescending
{
    bool operator()(const term&amp; t1, const term&amp; t2)
    { 
        return t2.pow < t1.pow; 
    }
};
Copy after login

By utilizing std::list<>::sort with the SortDescending comparator, you can successfully sort your list in descending order based on the 'pow' member of the 'term' structure.

The above is the detailed content of Why Does `std::sort` Fail to Sort a `std::list` of Structures?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template