Objects with more / less functionality in C ++

I looked at the documentation on object functions for more, less. Although I understand what’s in it, I don’t understand yet. Will a larger container be used in ascending or descending order? I am particularly confused because the next two lines seem to do the opposite.

std::priority_queue<int, std::vector<int>, std::greater<int> > q2; for(int n : {1,8,5,6,3,4,0,9,7,2}) q2.push(n); print_queue(p2); 

Fingerprints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. But

 int x[10] = { 1,3,5,7,9,2,4,6,8,10 }; std::sort(x,x+10,std::greater<int>()); 

Printing this file will give 10, 9, 8, 7, 6, 5, 4, 3, 2, 1.

It would be nice if someone could describe how the “more” works in my examples, instead of just saying how the “more” works in general.

+6
source share
2 answers

It will increase, you will always expose the smallest element of the queue. The priority queue is sorted by the inverse of the ordinal relation that it is specified.

The default template definition is as follows:

 template< class T, class Container = std::vector<T>, class Compare = std::less<typename Container::value_type> > class priority_queue; 

less<>()(lhs, rhs) is used to get the "largest" rhs element. But in your case, it will use greater<>()(lhs, rhs) to get the "largest" rhs element (which, of course, will be the smallest).

std::sort , on the other hand, saves the type of order you give it. Therefore, std::less will be sorted in ascending order and std::greater in descending order.

+4
source

std::greater<int> inverts the sort order of integers.

std::priority_queue decompresses the next largest element by default , so by using std::greater<int> you invert this to undo the next smallest element.

Similarly, std::sort will sort the items in ascending order by default, but using std::greater<int> , you will see a descending sort order.

+1
source

Source: https://habr.com/ru/post/1012681/


All Articles