[英]what is custom comparator and how to use it in the sort function in c++?
vector<vector<int>> reconstructQueue(vector<vector<int>> &people) {
auto cmp = [](const vector<int> &a, const vector<int> &b) {
return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]);
};
sort(people.begin(), people.end(), cmp);
Hey guys can someone explain me the auto cmp... part and how to use it in a sort function any help will be highly appreciated :)嘿伙计们,有人可以向我解释 auto cmp ... 部分以及如何在排序功能中使用它,任何帮助将不胜感激:)
This part of the code is a lambda .这部分代码是一个lambda 。 In other words, a small function defined locally.
换句话说,一个本地定义的小函数。 You can make a search for this term for more info.
您可以搜索此词以获取更多信息。
IN the case of the sort algorithm, you are expected to pass a function taking two arguments and returning true if the first argument is less than the second.在排序算法的情况下,您应该传递一个带有两个参数的函数,如果第一个参数小于第二个参数,则返回 true。 To make it simple, you give an alternative comparison function to use instead of the standard
operator<
aka std::less.为简单起见,您提供了一个替代的比较函数来代替标准
operator<
aka std::less。 Any object having an operator()
can be used.可以使用任何具有
operator()
对象。
The comparator can be implemented in multiple ways, for eg.比较器可以通过多种方式实现,例如。 a lambda (as in your example) or a callable struct/class.
一个 lambda(如你的例子)或一个可调用的结构/类。 Just to give you an example for sorting say a vector of std::pair by the second element:
只是为了给你一个排序的例子,说一个 std::pair 向量按第二个元素:
struct Comparator
{
bool operator()(const std::pair<int,int>& lhs, const std::pair<int,int>& rhs)
{
return lhs.second < rhs.second;
}
}
void foo(std::vector<std::pair<int,int> > &v)
{
std::sort(v.begin(), v.end(), Comparator);
}
Alternatively, instead of using a callable struct, you can write foo using lambda as:或者,您可以使用 lambda 将 foo 编写为:
void foo(std::vector<std::pair<int,int> > &v)
{
std::sort(v.begin(), v.end(),
[](const pair<int, int>& lhs, const pair<int, int>& rhs)
{
return lhs.second < rhs.second;
} );
}
You can write more advanced comparisons by say capturing some other data and using that for comparisons.您可以通过捕获一些其他数据并将其用于比较来编写更高级的比较。 Try reading about lambdas .
尝试阅读有关lambdas 的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.