# Sorting Vector of Pairs in C++ | Set 2 (Sort in descending order by first and second)

We have discussed some of the cases of sorting vector of pairs in below set 1.

Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)

Sometimes we require to sort the vector in reverse order. In those instances, rather than first sorting the vector and later using “reverse” function increases time complexity of code. Therefore, to avoid this we sort the vector in descending order directly.

Case 3 : Sorting the vector elements on the basis of first element of pairs in descending order.

For these instances, we modify the sort() function and we pass a third argument, a call to an user defined explicit function in the sort() function.

 `// C++ program to demonstrate sorting in vector of ` `// pair according to 1st element of pair in  ` `// descending order ` `#include ` `using` `namespace` `std; ` ` `  `// Driver function to sort the vector elements by  ` `// first element of pair in descending order ` `bool` `sortinrev(``const` `pair<``int``,``int``> &a,  ` `               ``const` `pair<``int``,``int``> &b) ` `{ ` `       ``return` `(a.first > b.first); ` `} ` ` `  `int` `main() ` `{ ` `    ``// declaring vector of pairs ` `    ``vector< pair <``int``,``int``> > vect; ` ` `  `    ``// initializing 1st and 2nd element of ` `    ``// pairs with array values ` `    ``int` `arr[] = {5, 20, 10, 40 }; ` `    ``int` `arr1[] = {30, 60, 20, 50}; ` `    ``int` `n = ``sizeof``(arr)/``sizeof``(arr); ` ` `  `    ``// Entering values in vector of pairs ` `    ``for` `(``int` `i=0; i

Output:

```The vector before applying sort is:
5 30
20 60
10 20
40 50
The vector after applying sort is:
40 50
20 60
10 20
5 30
```

Case 4 : Sorting the vector elements on the basis of second element of pairs in descending order.

These instances can also be handled by modifying “sort()” function and again passing a call to user defined function.

 `// C++ program to demonstrate sorting/in vector of ` `// pair according to 2nd element of pair in  ` `// descending order ` `#include ` `using` `namespace` `std; ` ` `  `// Driver function to sort the vector elements by ` `// second element of pair in descending order ` `bool` `sortbysecdesc(``const` `pair<``int``,``int``> &a, ` `                   ``const` `pair<``int``,``int``> &b) ` `{ ` `       ``return` `a.second>b.second; ` `} ` ` `  ` `  `int` `main() ` `{ ` `    ``// Declaring vector of pairs ` `    ``vector< pair <``int``,``int``> > vect; ` ` `  `    ``// Initializing 1st and 2nd element of ` `    ``// pairs with array values ` `    ``int` `arr[] = {5, 20, 10, 40 }; ` `    ``int` `arr1[] = {30, 60, 20, 50}; ` `    ``int` `n = ``sizeof``(arr)/``sizeof``(arr); ` ` `  `    ``// Entering values in vector of pairs  ` `    ``for` `(``int` `i=0; i

Output:

```The vector before sort operation is:
5 30
20 60
10 20
40 50
The vector after applying sort operation is:
20 60
40 50
5 30
10 20
```