Próbowałem użyć funkcji lambda z sort
, ale wystąpiły błędy "Błąd segmentacji". Udało mi się uprościć kod do następujących:Czy std :: sort działa z funkcją lambda w C++ 0x/C++ 11?
#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;
}
skompilować i uruchomić ten kod w Ubuntu 11.04 (x64) za pomocą
g++ -std=gnu++0x test2.cpp && ./a.out
.
Drukuje wiele par formularza (large_integer, 1008), kilka (0, 1008) i wyjść z "Błąd segmentacji".
Pamiętaj, że sortujesz tylko 17 pierwszych elementów za pomocą kodu. –
Tak. Ten fakt został odnotowany w jedynym komentarzu do kodu. – fiktor
@KerrekSB: "// Następujące elementy mają sortować wszystkie oprócz ostatniego elementu tablicy" – Griwes