std::sort 是否应该与 c++0x/c++11 中的 lambda 函数一起使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7767998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should std::sort work with lambda function in c++0x/c++11?
提问by fiktor
I tried to use lambda function with sort
, but was getting "Segmentation fault" errors. I managed to simplify the code to the following:
我尝试将 lambda 函数与 一起使用sort
,但出现“分段错误”错误。我设法将代码简化为以下内容:
#include <iostream>
#include <algorithm>
int main()
{
const int len = 18;
int intArr[len];
for (int i=0;i<len;i++) intArr[i]=1000+i;
// The following is expected to sort all but the last element of the array
std::sort(intArr, intArr + len -1, [](int a, int b)
{
std::cout<<"("<<a<<", "<<b<<")\n";
return (a<b?-1:(a>b?1:0));
});
return 0;
}
I compile and run this code in Ubuntu 11.04 (x64) using
我使用以下命令在 Ubuntu 11.04 (x64) 中编译并运行此代码
g++ -std=gnu++0x test2.cpp && ./a.out
.
g++ -std=gnu++0x test2.cpp && ./a.out
.
It prints a lot of pairs of the form (large_integer, 1008), a couple of (0, 1008) and exits with "Segmentation fault".
它打印了很多对的形式 (large_integer, 1008)、一对 (0, 1008) 并以“分段错误”退出。
回答by ybungalobill
The comparison predicate should return a bool: true if a < b and false otherwise. Change the return statement to:
比较谓词应返回 bool: true 如果 a < b 否则为 false。将返回语句更改为:
return a < b;
Don't confuse it with C-style 3-way comparison functions.
不要将它与 C 风格的 3 路比较函数混淆。
回答by Kerrek SB
The predicate is supposed to implement a simple, weak ordering. Also your range is off if you want to sort the entire thing.(I missed that that was intentional.) So all in all we're looking for something like this:
谓词应该实现一个简单的弱排序。如果您想对整个事物进行排序,那么您的范围也会关闭。(我错过了这是故意的。)所以总而言之,我们正在寻找这样的东西:
std::sort(intArr, intArr + nelems, [](int a, int b){ return a < b; });
Or even:
甚至:
std::sort(intArr, intArr + nelems);
The default predicate for sorting is std::less<T>
, which does exactly what the lambda does.
排序的默认谓词是std::less<T>
,它完全符合 lambda 的作用。
回答by Dave S
The predicate for std::sort
doesn't take the Java-like -1,0,1
, but instead wants you to return a boolean that answers the question 'Is the first argument less than the second argument?', which is used to weakly order the elements. Since -1
is a non-zero value, it is considered true by the sort algorithm, and it causes the algorithm to have a breakdown.
谓词 forstd::sort
不采用类似 Java 的-1,0,1
,而是希望您返回一个布尔值来回答问题“第一个参数是否小于第二个参数?”,用于对元素进行弱排序。由于-1
是一个非零值,排序算法认为它为真,并导致算法出现故障。