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];});
a
is a variable of type vector<vector<int>>
.
a[i][0]
means the key of the i
th element
the purpose of those code is to sort a
by key
So we need to pass a self defined compare function when calling "sort()"
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:
Lambda expression
[](auto &x, auto &x){return x[0] < y[0];}
Comparison function
bool comp(vector<int>& x, vector<int>& y) { return x[0] < y[0]; } sort(a.begin(), a.end(), comp);
a
is avector<vector<int>>
x
andy
are elements ofa
ievector<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 ina
.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.