How does comparator work with inbuilt sort function of c++?

Viewed 47

So I'm currently learning 2D arrays in c++, I was solving this question which had a 2D array and we were to use sort inbuilt sort function of c++ with comparator, here's the code:

  int getLights(vector<vector<int>>& lights) {
  sort(lights.begin(),lights.end(),
             [](const auto& a, const auto& b){
                 return a[0]==b[0] ? a[1]>b[1] : a[0]<b[0];
             });
        

I'm not able to understand how this sort function works, can anyone help me get the output with this input:

lights = [[5,5],[6,3],[3,6]]
2 Answers

The C++'s built in sort that you are using takes the first and last element of the array to be sorted to know what has to be sorted. The third argument is a "comparator", i.e. a function that takes two arguments and returns true if the first argument should come before the second.

In your case a vector a comes before other b if its first element a[0] is smaller the other's b[0], and if they are the same then a comes first if a[1] > b[1]. To archive this logic the conditional operator (E1 ? E2 : E3) is used, which checks the truth value of the first expresión and returns the second if it's true and the third expresión if it's false.

C++ STL provides a function sort that sorts a vector or array (items with random access)

It generally takes two parameters, the first being the point of the array/vector from where the sorting needs to begin and the second parameter being the length to which we want the array/vector to get sorted. The third parameter is optional and can be used in cases where we want to sort the elements lexicographically.

By default, the sort() function sorts the elements in ascending order.

How to sort in a particular order?

We can also write our own comparator function and pass it as a third parameter. This “comparator” function returns a value; convertible to bool, which basically tells us whether the passed “first” argument should be placed before the given “second” argument or not.

Source: Sort C STL

The function you have written as the 3rd argument act as a comparator (it is a lambda expression), which returns a boolean value.

return a[0]==b[0] ? a[1]>b[1] : a[0]<b[0];

This statement basically compares the elements of a and b, if 1st element is the same check for the second element. It returns the smallest of the two numbers with respect to the 1st element of both arrays.

Output: [[3,6],[5,5],[6,3]]
Related