How to sort a vector of pairs in C++

In this post, we will discuss how to sort a vector of pairs in C++.


 

1. Default comparator of pair

The recommended approach is to use 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 call to operator< or in decreasing order of their first value using std::greater<> which will delegate 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 first value of two pairs are equal, they will be compared based on their second value.

 

2. Custom Comparator

If you don't want to use the default ordering, 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 prior to the second value. A comparator can be a binary function, an instance of class with operator() overload (a functor) or even an anonymous closure (lambda). Let's 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}

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of