C++ sort with comparator greater

Introduction

There is a built-in comparator called std::greater, which does the comparisons using the operator > and allows the std::sort function to sort the data in ascending order.

Example:

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

int main() //from  w  w  w.  j  a va  2s . c o  m
{ 
    std::vector<int> v = { 1, 5, 2, 15, 3, 10 }; 
    std::sort(v.begin(), v.end(), std::greater<int>()); 
    for (auto el : v) 
    { 
        std::cout << el << '\n'; 
    } 
} 

Comparator or a comparison function is a so-called function object defined inside the <functional> header.

We can define our custom function object via the so-called unnamed functions called lambda functions or lambdas.

The third parameter of the std::sort function is often called a predicate.

A predicate is a function or a function object returning true or false.

Standard-library functions such as the std::sort accept predicates as one of their arguments.




PreviousNext

Related