与 stl sort() 的比较
我正在尝试在类函数中使用 stl sort() 。我想对如下所示的结构数组进行排序:
struct foo{
double num;
std::string s;
};
使用如下比较函数:
bool aGreaterThanb(foo a, foo b){
if (a.num > b.num){
if(a.num == b.num){
if (anotherOutsideComparison(a.s, b.s)){
return true;
}
}
else
return true;
}
else
return false;
}
但我不确定如何格式化它以使其进行编译。我应该如何格式化它以便我可以调用 sort(fooarray[0], fooarray[end], aGreaterThanb);
? (举个例子就太好了)
I'm trying to use stl sort() in a class function. I would like to sort an array of structs that look like this:
struct foo{
double num;
std::string s;
};
with a comparison function like this:
bool aGreaterThanb(foo a, foo b){
if (a.num > b.num){
if(a.num == b.num){
if (anotherOutsideComparison(a.s, b.s)){
return true;
}
}
else
return true;
}
else
return false;
}
But I'm not sure how I can format this to get it to compile. How should I format this so I can call sort(fooarray[0], fooarray[end], aGreaterThanb);
? (An example would be great)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
将比较函数编写为称为函子的结构的
operator()
方法:然后将该函子对象的实例传递给
std::sort
:Write your comparison function as the
operator()
method of a structure called a functor:Then pass an instance of that functor object to
std::sort
:如果您使用像这样的
foo
数组:上面的代码将以相反的顺序对数组进行排序,因为 sort 需要一个小于比较器。
此外,为了避免为了比较而复制大量
foo
对象,请声明您的比较器以const foo&
而不是foo
作为参数。If you are using an array of
foo
like this:The above code would sort your array in reverse order, since sort expects a less-than comparator.
Additionally to avoid copying a lot of
foo
-objects around just for comparison, declare your comparator to takeconst foo&
instead offoo
as arguments.您应该将迭代器(指针的广义超集)传递给 STL
sort
函数:You're supposed to pass iterators — a generalized superset of pointers — to the STL
sort
function:它已经按照您想要的方式工作了:
但是您有语法错误。您缺少一个大括号:
为了提高效率,您应该通过 const 引用传递:
It works just as you want already:
But you have syntax error. You are missing a brace:
For efficiency you should pass by const reference:
请注意,在最坏的情况下,排序函数最多进行 N^2 次比较。
stable_sort复杂度在N*logN和N*(LogN^2)之间
Note that in worst case sort function is up to N^2 comparsions.
And stable_sort complexity is between N*logN and N*(LogN^2)
让它成为一个运营商。
如果您确实想使用 operator> 进行排序,请传递 std::greater() 作为函子。
Make it an operator.
If you really want to sort using operator>, pass
std::greater<foo>()
as the functor.