Home  >  Article  >  Backend Development  >  Why am I getting "no match for 'operator-' in '__last - __first'" when sorting a list in descending order using STL sort?

Why am I getting "no match for 'operator-' in '__last - __first'" when sorting a list in descending order using STL sort?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 18:16:02903browse

Why am I getting

Sorting a List with STL sort Function

When sorting a list in descending order using the STL sort function, you may encounter a compilation error if your list contains items of a struct and the comparator function is not properly defined. The error "no match for 'operator-' in '__last - __first'" indicates that the sort function cannot determine the order of elements in your list.

The issue arises because the sort function requires random access iterators, which std::list::iterators are not. List iterators are bidirectional iterators, which cannot directly compute the difference between two iterators. This prevents the sort function from correctly calculating the range of elements to be sorted.

To resolve this issue, you should use the std::list::sort member function instead of the std::sort function. The std::list::sort function uses bidirectional iterators and can handle sorting of lists containing your struct.

Here's an example of how you can use the std::list::sort function to sort your list in descending order:

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

This custom comparator function will properly sort your list of structs in descending order based on the pow field within each struct.

The above is the detailed content of Why am I getting "no match for 'operator-' in '__last - __first'" when sorting a list in descending order using STL sort?. 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