In this blog we are going to discuss a better way to sort c++ stl vector in descending order. for example  if the given vector is  vector<int> vec = { 20, 10, 2, 8, 3 } then after sorting it should be 20,10,8,2,3.

c++ std::sort()

The syntax of std::sort() is

std::sort(numbers.begin(), numbers.end())
or
std::sort(numbers.begin(), numbers.end(), comparator);

By default without third parameter in sort() , it sorts elements of vector in increasing order.

How to sort c++ vector in descending order

To sort c++ stl vectors in descending order we need a custom comparator functions. Let us use std::greater<int>() standard function object. The function object std::greater has

bool operator() (const T& a, const T& b)
    Member function returning whether the first argument compares greater than the second (a>b).

sort c++ stl vector in descending order example

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    vector<int> vec = { 20, 10, 2, 8, 3 };

    sort(vec.begin(), vec.end(),greater<int>());

    // print using c++ 11 range
    for(auto a:vec){
        cout << a << " ";
    }
    cout << endl;
    return 0;
}

output:

20 10 8 3 2

A better way to sort c++ stl vector

The above implementation is not a good solution. why?

Because the the function object provided in sort() functions will only work for vectors containing integers type int. Let us write our own comparator function objects.

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct mygreater
{
    template<class T>
    bool operator()(T const &a, T const &b) const { return a > b; }
};

int main()
{
    vector<int> vec = { 20, 10, 2, 8, 3 };

    sort(vec.begin(), vec.end(),mygreater());

    // print using c++ 11 range
    for(auto a:vec){
        cout << a << " ";
    }
    cout << endl;
    return 0;
}

Now the code would work fine even if type is int,long or long long.

Learn more about c++ stl

How to use 2d vectors  in c++

How to delete row or column of c++ 2d vectors

Learn C++ Standard Template library a crash course by wikistack



Related Contents to follow