How to sort vector in descending order in C++

Hello, Coders!! In this section, we will learn how to sort a vector in descending order in C++.

Let’s discuss the methods, we can sort the vector:

  1. Using sort() function
  2. Using sort() + comparator

Sorting of the vector in descending order using sort() function

We can use the sort() function to sort either in increasing or decreasing order of the vector. The sort() function is imported from the algorithm header file of the C++ library to the program. It is a very high efficient implementation of the instrosort algorithm.

Syntax:

sort(first, last) //Here first and last is the range of elements to sort

 

By using operator< the sort() function we can sort the vector in ascending order. To sort in the descending order, call reverse() right after the sort().

Example:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<int> vec = { 6, 78, 14, 86, 99, 24 };
    
    cout << "Unsorted Vector: ";
    for (int i = 0; i < vec.size(); i++) {
          cout << vec[i] << " ";
    }
    cout << endl;
      
    sort(vec.begin(), vec.end());
    reverse(vec.begin(), vec.end());
    
    cout << "Sorted Vector(Descending order): ";
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    cout << endl;
        
    return 0;
}

Output:

Unsorted Vector: 6 78 14 86 99 24 
Sorted Vector(Descending order): 99 86 78 24 14 6

Sorting of the vector in descending order using sort()+comparator

There is an overloaded version of sort() that accepts a comparator. The comparator is basically a class that is used to compare user-defined class objects. It returns a boolean value by taking an argument.

We can use std::greater as a comparator. It will return a true value if the first argument value is bigger than the second argument.

We can skip the template argument in C++14. So, we can use greater<>() instead of greater<int>().

Example:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<int> vec = { 6, 78, 14, 86, 99, 24 };
    
    cout << "Unsorted Vector: ";
    for (int i = 0; i < vec.size(); i++) {
          cout << vec[i] << " ";
    }
    cout << endl;
      
    std::sort(vec.begin(), vec.end(), greater<int>());
    
    cout << "Sorted Vector(Descending order): ";
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    cout << endl;
        
    return 0;
}

Output:

Unsorted Vector: 6 78 14 86 99 24 
Sorted Vector(Descending order): 99 86 78 24 14 6

I hope with the help of this article you have learned how to sort any vector in descending order in a C++ program easily.

Keep Learning!!!

You can also read, Removing elements from a Vector in C++

Leave a Reply

Your email address will not be published. Required fields are marked *