应该在c ++ 0x / c ++ 11中使用lambda函数进行std :: sort工作? [英] Should std::sort work with lambda function in c++0x/c++11?
问题描述
我试图用 sort
使用lambda函数,但是正在获得分段错误错误。我设法简化了以下代码:
I tried to use lambda function with sort
, but was getting "Segmentation fault" errors. I managed to simplify the code to the following:
#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;
}
我在Ubuntu 11.04(x64)中编译并运行此代码,使用
I compile and run this code in Ubuntu 11.04 (x64) using
g ++ -std = gnu ++ 0x test2.cpp&&& ./a.out
。
它打印了很多对的形式(large_integer,1008),几个(0,1008 )并退出Segmentation fault。
It prints a lot of pairs of the form (large_integer, 1008), a couple of (0, 1008) and exits with "Segmentation fault".
推荐答案
比较谓词应该返回一个bool:true如果< b否则为false。将返回语句更改为:
The comparison predicate should return a bool: true if a < b and false otherwise. Change the return statement to:
return a < b;
不要将其与C风格的3路比较功能混淆。
Don't confuse it with C-style 3-way comparison functions.
这篇关于应该在c ++ 0x / c ++ 11中使用lambda函数进行std :: sort工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!