Compiler Error on std::sort function (GCC 4.4)

1.6k Views Asked by At

The code below sorting in Visual Studio successfully.
But, in Ubuntu GCC 4.4.7 compiler throws error. It seems it's not familiar with this type of syntax. How shall I fix this line to make code working in GCC? (the compiler is remote. So I can't upgrade the GCC version either). What I'm doing right here is:sorting Vector B elements regarding their fitness values

//B is a Vector of class Bird
//fitness is a double - member of Bird objects

vector<Bird> Clone = B;

    sort(Clone.begin(), Clone.end(), [](Bird a, Bird b) { return a.fitness> b.fitness; });

//error: expected primary expresssion before '[' token
//error: expected primary expresssion before ']' token...

(Note: this 3 piece of lines compiling successful in MSVC but not in GCC)


my answer is

bool X_less(Bird a, Bird b) { return a.fitness > b.fitness; }

std::sort(Clone.begin(), Clone.end(), &X_less);

It seems to work. Is it a function or not? I don't know its technical name, but it seems to work. I am not much familiar with C++.

1

There are 1 best solutions below

4
On

You will need to upgrade your C++ as 4.4 is too old to support Lambda. I have Gcc 4.8, but it still requires you enable c++11 that includes lambda functions, so

$ g++  -std=c++11  x.cc

compiles this fine

#include <algorithm>
#include <functional>
#include <vector>

using namespace std;

int main()
{
    vector<int> Clone;

    sort(Clone.begin(), Clone.end(), [](int a, int b) { return a> b; });
}

but still gives errors without -std=c++11 option