Summary of comparison functions for sort and priority_queue

For priority_queue, the comparison function is (if it is not a structure, direct int, the default for the priority queue is that the larger the value, the greater the priority):

struct st
{
    string str;
    int pr, value,mark ;
    bool operator < (const st&a)const
    {
        if (pr !=a.pr) return pr > a.pr; // The smaller the value, the higher the priority 
        return mark > a.mark; // The smaller the value, the higher the priority 
    }
};

And for sort

1 #include<iostream>
 2 #include<algorithm>
 3  using  namespace std;
 4  int cmp( int a, int b)
 5  {
 6      return a > b; // Sort from largest to smallest 
7  }
 8  int main()
 9  {
 10      int a[] = { 2 , 1 , 4 , 3 , 4 , 5 , 1 , 3 };
 11      sort(a, a + 8, cmp);
12     for (int i = 0; i < 8; i++)
13         cout << a[i] << " ";
14     return 0;
15 }

greater<int>()//From big to small

less<int>()//From small to large

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325859022&siteId=291194637