简体   繁体   中英

A question about creating temporary functions in C++

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 i th element

  3. the purpose of those code is to sort a by 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?

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 ie vector<int>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM