This post will discuss how to sort a vector of pairs in C++.

1. Default comparator of pair

The recommended approach uses the standard algorithm std::sort defined in the <algorithm> header. It takes the iterators to the initial and final positions of the vector, and sorts pairs in increasing order of their first value using std::less<> which will delegate the call to operator< or in decreasing order of their first value using std::greater<> which will delegate the call to operator>.

Download  Run Code

Output:

{1,2}
{3,4}
{6,1}
{6,4}

 
This works as less-than, and greater-than operators are already defined for the pair class. Notice that if the first value of two pairs is equal, they will be compared based on their second value.

2. Using Custom Comparator

If you don’t want to use the default order, you can write your own comparator and pass it to the std::sort function. A comparator takes two pair objects and returns a bool indicating whether to put the first value before the second value. A comparator can be a binary function, an instance of a class with operator() overload (a functor), or even an anonymous closure (lambda). Lets demonstrates these:

1. Lambda expressions (C++11 and above)

Download  Run Code

Output:

{4,1}
{1,2}
{3,4}
{6,4}

2. Passing object of a class implementing () operator

Download  Run Code

Output:

{4,1}
{1,2}
{3,4}
{6,4}

3. Using binary function

Download  Run Code

Output:

{4,1}
{1,2}
{3,4}
{6,4}

That’s all about sorting a vector of pairs in C++.