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());
Note that the std::list<>::sort member function also requires a comparator function. The SortDescending comparator remains unchanged:
struct SortDescending { bool operator()(const term& t1, const term& t2) { return t2.pow < t1.pow; } };
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!