A question about creating temporary functions in C++

Viewed 71

I have a very basic C++ question. But I didn't find an appropriate answer after my own search. I saw some C++ code written like this:

sort(a.begin(), a.end(), [](auto &a, auto &b){return a[0] < b[0];});
  1. a is a variable of type vector<vector<int>>.

  2. a[i][0] means the key of the ith element

  3. the purpose of those code is to sort aby key

  4. So we need to pass a self defined compare function when calling "sort()"

  5. the self defined compare function is defined by these codes:

    [](auto &a,auto &b){return a[0] < b[0];}
    

I've never seen this way of writing (just like a lambda function in C++!), could you tell me how to understand these code?

1 Answers

As per your question:

    sort(a.begin(), a.end(), [](auto &a, auto &b){return a[0] < b[0];});

a.begin()[First], a.end()[Last] - range of elements to sort

for the 3rd parameter, there are two options:

  1. Lambda expression

     [](auto &x, auto &x){return x[0] < y[0];}
    
  2. Comparison function

     bool comp(vector<int>& x, vector<int>& y) {
         return x[0] < y[0];
     }
    
     sort(a.begin(), a.end(), comp);
    

a is a vector<vector<int>>

x and y are elements of a i.e. vector<int>

Tip: To avoid confusion, don't re-use the name a in the lambda expression(like I used x and y to avoid confusion)

The lambda expression or the comparison function takes a pair of elements from a and sorts them based on the first value(x[0]) of each element in a.

If you see, both are very similar.

a. Both accept an argument list. (x and y in this case)

b. Both have a body return x[0] < y[0];

I hope this answers all of your questions.

Related