Home >Backend Development >C++ >Why Can't I Sort a List in Descending Order Using `std::sort` and a Custom Comparator?

Why Can't I Sort a List in Descending Order Using `std::sort` and a Custom Comparator?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 16:53:28491browse

Why Can't I Sort a List in Descending Order Using `std::sort` and a Custom Comparator?

Sorting Lists Using STL Sort Function

Implementing list sorting in descending order can be challenging when the list contains objects of a custom struct. However, the issue you encountered, "no match for 'operator-' in '__last - __first'", reveals a deeper problem with the chosen sorting approach.

The provided SortDescending struct correctly defines an operator to compare two terms, but it does so based on their power, t2.pow < t1.pow. This comparison, however, is incompatible with the standard sort function.

The problem stems from the fact that std::sort requires random access iterators, which list iterators do not provide. Bidirectional iterators, like those in std::list, allow you to move through the list, but they lack the necessary capabilities to perform direct access or pointer arithmetic.

To sort a list using the STL sort function, random access iterators must be available. An alternative approach is to use the member function std::list::sort. This function accepts a comparator function as an argument, enabling you to define a customized sorting criteria.

In your case, the following code will sort the list in descending order based on the power of its terms:

Result.poly.sort([](const term& t1, const term& t2) { return t1.pow > t2.pow; });

By using the correct iterators and appropriate sorting function, you can effectively sort your list in the desired order.

The above is the detailed content of Why Can't I Sort a List in Descending Order Using `std::sort` and a Custom Comparator?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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